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

后端 未结 5 1216
春和景丽
春和景丽 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条回答
  •  时光说笑
    2020-11-29 03:48

    A simpler version of the solution by jcalz:

    type AtLeastOne = { [K in keyof T]: Pick }[keyof T]

    so the whole implementation becomes

    type FullLinkRestSource = {
      model: string;
      rel: string;
      title: string;
    }
    
    type AtLeastOne = { [K in keyof T]: Pick }[keyof T]
    type LinkRestSource = AtLeastOne
    
    const okay0: LinkRestSource = { model: 'a', rel: 'b', title: 'c' }
    const okay1: LinkRestSource = { model: 'a', rel: 'b' }
    const okay2: LinkRestSource = { model: 'a' }
    const okay3: LinkRestSource = { rel: 'b' }
    const okay4: LinkRestSource = { title: 'c' }
    
    const error0: LinkRestSource = {} // missing property
    const error1: LinkRestSource = { model: 'a', titel: 'c' } // excess property on string literal
    

    and here's the TS playground link to try it

提交回复
热议问题