Typescript: Property type wildcard

不想你离开。 提交于 2021-02-11 06:42:33

问题


I have a given interface which comes from another package, so I can't really change it. For the sake of simplicity, let's just say the following interface:

interface SomeInterface {
   someProp: string;
   someOtherProp?: number;
}

I was wondering if I can somehow extract the types of all properties so I would get a combined type which could be any of the original Interface's properties.

In the example, it would resolve to a type being string | number | undefined.

Also, not really the same question, but quite related to it. Is it possible to extract the allowed properties names instead of values, so in the example given it would be a type holding the values "someProp" | "someOtherProp".

For the first case, I already tried the type SomeInterface[string], but I think that only works when the interface has a key/index signature defined, not specific properties.


回答1:


Get all possible keys of Mapped type by keyof

type Keys = keyof SomeInterface;

Get all possible values of Mapped type by indexed access operator

type Values = SomeInterface[keyof SomeInterface];


来源:https://stackoverflow.com/questions/60076526/typescript-property-type-wildcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!