如何在打字稿中实现联合类型的对象值
How can I achieve a union type of object values in typescript
const obj = {
a: 122,
b: 456,
c: '123',
};
// Keys = "a" | "b" | "c"
type Keys = keyof typeof obj;
// Values = string | number"
type Values = typeof obj[Keys];
const a: Values = '1234'; // => should throw an error
我正在寻找一种获取联合类型的方法,如下所示:123 | 456 | '123'
结合使用 as const
、keyof
和 typeof
,您可以实现这一目标。使用 as consts
对象变得不可变并且 Typescript 能够使用键提取值。
const obj = {
a: 122,
b: 456,
c: '123',
} as const // use 'as const' here
// Keys = "a" | "b" | "c"
type Keys = keyof typeof obj
// Values = 122 | 456 | "123"
type Values = typeof obj[Keys]
这是对 as const
功能的一个很好的解释顺便说一句:
const obj = {
a: 122,
b: 456,
c: '123',
};
// Keys = "a" | "b" | "c"
type Keys = keyof typeof obj;
// Values = string | number"
type Values = typeof obj[Keys];
const a: Values = '1234'; // => should throw an error
我正在寻找一种获取联合类型的方法,如下所示:123 | 456 | '123'
结合使用 as const
、keyof
和 typeof
,您可以实现这一目标。使用 as consts
对象变得不可变并且 Typescript 能够使用键提取值。
const obj = {
a: 122,
b: 456,
c: '123',
} as const // use 'as const' here
// Keys = "a" | "b" | "c"
type Keys = keyof typeof obj
// Values = 122 | 456 | "123"
type Values = typeof obj[Keys]
这是对 as const
功能的一个很好的解释顺便说一句: