Make some properties optional in a TypeScript type

前端 未结 2 561
-上瘾入骨i
-上瘾入骨i 2020-12-29 12:02

If I have a type with all required properties, how can I define another type with the same properties where some of it\'s properties are still required but the rest are opti

相关标签:
2条回答
  • 2020-12-29 12:40

    You can use combination of Partial and Pick to make all properties partial and then pick only some that are required:

    interface SomeType {
        prop1: string;
        prop2: string;
        prop3: string;
        propn: string;
    }
    
    type OptionalExceptFor<T, TRequired extends keyof T> = Partial<T> & Pick<T, TRequired>
    
    type NewType = OptionalExceptFor<SomeType, 'prop1' | 'prop2'>
    
    let o : NewType = {
        prop1: "",
        prop2: ""
    }
    
    0 讨论(0)
  • 2020-12-29 12:48

    For tetter performance, in addition to Titian's answer, you must do :

    type OptionalExceptFor<T, TRequired extends keyof T = keyof T> = Partial<
      Pick<T, Exclude<keyof T, TRequired>>
    > &
      Required<Pick<T, TRequired>>;
    
    0 讨论(0)
提交回复
热议问题