Make some properties optional in a TypeScript type

前端 未结 2 577
-上瘾入骨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 = Partial & Pick
    
    type NewType = OptionalExceptFor
    
    let o : NewType = {
        prop1: "",
        prop2: ""
    }
    

提交回复
热议问题