[英]Use keys of an object as union-type
I've got a object (let it be frozen so typescript may handle its keys better):我有一个对象(让它被冻结,这样打字稿可以更好地处理它的键):
const obj = Object.freeze({
'hello': 64,
'world': 20
}) as {[key: string]: number};
Now I have a function where the user can pick values by their keys:现在我有一个功能,用户可以通过他们的键选择值:
const pick = (keys: Array<string>): Array<number> => {
const values = [];
for (const key of keys) {
// Check if object contains property-key
if (!(key in obj)) {
throw new Error(`There's no such key: ${key}`);
}
values.push(obj[key]);
}
return values;
};
That's looking good so far and works flawlessly during runtime where I check if the user passed any invalid keys.到目前为止看起来不错,并且在运行时运行时完美无缺,我检查用户是否传递了任何无效密钥。 But how can I tell TS that only keys from
obj
can be used?但是我怎么能告诉 TS 只能使用来自
obj
键呢?
I could do Array<'hello' | 'world'>
我可以做
Array<'hello' | 'world'>
Array<'hello' | 'world'>
but I'd need to update it any time I add new properties to obj
which is kinda annoying. Array<'hello' | 'world'>
但我每次向obj
添加新属性时都需要更新它,这有点烦人。
Related questions but they all seem to use types whereas I only have a object (which can be frozen if that helps):相关问题,但它们似乎都使用类型,而我只有一个对象(如果有帮助,可以将其冻结):
type
whereas I'm trying to build a type out of my object) type
而我正试图从我的对象中构建一个类型)const obj = Object.freeze({
'hello': 64,
'world': 20
});
const pick = (keys: Array<keyof typeof obj>) {...}
As you can see I have removed as {[key: string]: number};
如您所见,我已将其删除
as {[key: string]: number};
as it was widening the type, where you wanted to have it strict.因为它正在扩大类型,您希望它严格。
Next things is Array<keyof typeof obj>
I declare here that I accept as argument only array of keys from type of obj
.接下来是
Array<keyof typeof obj>
我在这里声明我只接受来自obj
类型的键数组作为参数。
Array<keyof typeof obj>
evaluates dynamically into ("hello" | "world")[]
, fortunately as you wanted it will reflect every change in original obj
Array<keyof typeof obj>
动态计算为("hello" | "world")[]
,幸运的是它会反映原始obj
每一个变化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.