Does Typescript support “subset types”?

后端 未结 7 1755
青春惊慌失措
青春惊慌失措 2020-12-29 02:36

Let\'s say I have an interface:

interface IUser {
  email: string;
  id: number;
  phone: string;
};

Then I have a function that expects a

7条回答
  •  不思量自难忘°
    2020-12-29 02:52

    If I understand this question correctly, you want something like Flow's $Shape

    So, in one place, you may have something that requires the type

    interface IUser {
      email: string;
      id: number;
      phone: string;
    };
    

    Then, in another place you want a the type with the same type as IUser just with all the fields now optional.

    interface IUserOptional {
      email?: string;
      id?: number;
      phone?: string;
    };
    

    You want a way to auto-generate IUserOptional based on IUser without having to write out the types again.

    Now, I don't think this is possible in Typescript. Things may change in 2.0, but I don't think we're even close to something like this in Typescript yet.

    You could look at a pre-compiler which would generate such code for you before typescript runs, but that doesn't sound like a trivial thing to do.

    With this problem in mind, I can only suggest you try Flow instead. In flow you can just do $Shape to generate the type you want programmatically. Of course, Flow differs from Typescript in many big and small ways, so keep that in mind. Flow is not a compiler, so you won't get things like Enums and class implementing interfactes

提交回复
热议问题