【发布时间】:2022-01-09 17:22:10
【问题描述】:
我想键入一个键值相同的对象:
const myObj = {
FOO: 'FOO',
BAR: 'BAR'
};
我尝试使用myObj 和key 设置typeof:
const actions: { [x: string]: x } = { // 'x' refers to a value, but is being used as a type here. Did you mean 'typeof x'?
set: 'set1'
}
const actions: { [x: string]: typeof x } = {
set: 'set1' // doesn't trigger
}
const actions: { [p: string]: keyof typeof actions } = {
set: 'set' // Type 'string' is not assignable to type 'never'.
}
type K = 'set' | 'set2';
const actions: { [p in K]: K } = { // triggers missing set2
set: 'set1' // doesn't trigger
}
有没有一种方法可以确保键和值始终匹配?蒂亚!
【问题讨论】:
-
Set对象只有 key 属性,您也可以将其用作值 -
@Berkays 你能举个例子吗?我以前没有在 typescript 中使用过 Set ..
标签: javascript typescript types