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}

Share Improve this question edited Jan 29 at 9:21 jonrsharpe 122k30 gold badges267 silver badges474 bronze badges asked Jan 29 at 9:11 Dan.Dan. 7271 gold badge8 silver badges23 bronze badges 1
  • 1 Thing[keyof Thing]? – jonrsharpe Commented Jan 29 at 9:21
Add a comment  | 

1 Answer 1

Reset to default 1

You can use it like this:

interface MyInterface {
   a: string;
   b: number;
}

type MyType = MyInterface[keyof MyInterface];

const test1: MyType = "abc";
const test2: MyType = 55;

本文标签: typescriptDeclare a type that is a union of the types of the properties of an interfaceStack Overflow