Does Typescript support “subset types”?

后端 未结 7 1682
青春惊慌失措
青春惊慌失措 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:58

    What you want is this

    type Subset<T extends U, U> = U;
    

    this makes sure, that U is a subset of T and returns U as a new type. for example:

    interface Foo {
     name: string;
     age: number;
    }
    
    type Bar = Subset<Foo, {
     name: string;
    }>;
    

    you can not add new properties to Bar which are not part of Foo - and you can not alter types in a non-compatible way. this also works recursively on nested objects.

    0 讨论(0)
提交回复
热议问题