How to create a Partial-like that requires a single property to be set

后端 未结 5 1198
春和景丽
春和景丽 2020-11-29 03:24

We have a structure that is like the following:

export type LinkRestSource = {
    model: string;
    rel?: string;
    title?: string;
} | {
    model?: str         


        
5条回答
  •  -上瘾入骨i
    2020-11-29 04:09

    That would not be possible with Partial. Under the hood it looks like this:

    type Partial = { [P in keyof T]?: T[P]; };
    

    All properties made optional.

    I doubt it is possible (or easy) to enforce your rule via type system.

    Could try to create type that employs keyof in a similar way, but have a condition in default constructor.

    If you can think of a way to declare a type like Partial that builds a matrix of types like yours emitting ? for a different key in each and concat all of them using | like in your first example, you might be able to enforce your rule vie type system.

    This blog post on keyof might give you some ideas.

提交回复
热议问题