admin管理员组文章数量:1316669
I have an interface:
{
a: string,
b: number
}
I want to make a type that can, based on the above interface, be either a string or a number. So, a type
that 'does the same thing' as the following:
type MyType = string | number
But created based from the interface, like type MyType = {any type from the properties of the interface}
I have an interface:
{
a: string,
b: number
}
I want to make a type that can, based on the above interface, be either a string or a number. So, a type
that 'does the same thing' as the following:
type MyType = string | number
But created based from the interface, like type MyType = {any type from the properties of the interface}
1 Answer
Reset to default 1You can use it like this:
interface MyInterface {
a: string;
b: number;
}
type MyType = MyInterface[keyof MyInterface];
const test1: MyType = "abc";
const test2: MyType = 55;
版权声明:本文标题:typescript - Declare a type that is a union of the types of the properties of an interface - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742007516a2412260.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
Thing[keyof Thing]
? – jonrsharpe Commented Jan 29 at 9:21