我希望将对象的可分配类型限制为特定类型。例如,所有键都必须具有number值的对象,如下所示:
interface NumberMap {
[key: string]: number;
}这对于强制执行值限制是有效的,但是这样我就无法确定map变量中实际存在哪些键。
const map: NumberMap = {
one: 1,
two: 2,
three: 3,
};
// no error, but incorrect, this key does *not* exist
const lol = map.weoiroweiroew;
// Also cannot do this
type MyKeys = keyof map;是否有一种在不丢失实现该签名的对象具有哪些密钥的情况下强制执行索引签名的方法?
发布于 2018-06-13 11:41:08
这两种限制值以及保存有关实现类型中的键的类型信息的唯一方法是使用泛型助手函数。函数将强制对象文字扩展接口,但它将推断对象文字的实际类型:
interface NumberMap {
[key: string]: number;
}
function createNumberMap<T extends NumberMap>(v: T) {
return v;
}
const map = createNumberMap({
one: 1,
two: 2,
three: 3,
// no: '' // error
});
map.one //ok
map.no //error发布于 2020-08-05 19:06:57
这个怎么样?我认为这会将对象键限制在给定的3个索引上。
type Index = 'one' | 'two' | 'three'
type NumberMap = { [k in Index]?: number }https://stackoverflow.com/questions/50836259
复制相似问题