我有打字稿的问题。我想从对象值创建像union这样的东西。我怎么能做到这一点?例如:
const x = {
x: 1,
y: 2,
z: 'a string',
k: document.createElement('div')
}
const y = (y: the value which exist of x ): boolean => {
return true
}
就像是:
type ValueOf<T> = T[keyof T];
但对于对象。任何提示都是受欢迎的。
要获得变量类型中的值的并集,可以使用ValueOf<typeof x>
。对于你的例子,类型将是string | number | HTMLDivElement
const x = {
x: 1,
y: 2,
z: 'a string',
k: document.createElement('div')
}
type ValueOf<T> = T[keyof T];
const y = (P: ValueOf<typeof x>): boolean => { // p: string | number | HTMLDivElement
return true
}
从评论中你想要的文字类型(1 | 2 | "a string"
)不是基本类型。为此,您需要更改类型pf x
以包含文字类型。最简单的方法是在3.4中添加一个const
断言:
const x = {
x: 1,
y: 2,
z: 'a string',
k: document.createElement('div')
} as const
type ValueOf<T> = T[keyof T];
const y = (p: ValueOf<typeof x>): boolean => { // p: 1 | 2 | "a string" | HTMLDivElement
return true
}
我想这就是你需要的:
export const xx = {
x: 1,
y: 2,
z: 'a string',
k: document.createElement('div')
};
type ValueOf<T> = T[keyof T];
type XValues = ValueOf<typeof xx>;