typescript - 创建基于键推断泛型的记录类型
问题描述
我想做这样的事情:
type PossibleKeys = "foo" | "bar" | "not-bar";
type SpecialRecord = Record<PossibleKeys, {
key: PossibleKeys; // I want to make sure that this key matches the record key.
data: number;
}> ;
const myRecord = {
foo: {
key: "foo", // Should be ok
data: 9,
},
bar : {
key: "not-bar", // Should error
data: 10
}
};
也就是说,我想声明我的SpecialRecord
类型,以便它强制记录的键与key
值的属性匹配。
这可能吗?
解决方案
这称为映射对象类型,您可以这样做:
type PossibleKeys = "foo" | "bar" | "not-bar";
type SpecialRecord = {
[K in PossibleKeys ]: {
key: K;
data: number;
}
}
const myRecord : SpecialRecord= {
foo: {
key: "foo",
data: 9,
},
bar : {
key: "not-bar", //Type '"not-bar"' is not assignable to type '"bar"'.(2322)
data: 10
}
};