简体   繁体   English

使用对象的键作为联合类型

[英]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):相关问题,但它们似乎都使用类型,而我只有一个对象(如果有帮助,可以将其冻结):

  1. Make union type of objects from type keys (He got a type, I'm with a object) 从类型键创建联合类型的对象(他有一个类型,我有一个对象)
  2. get union type of object keys filtered by type of object value (Basically the same as 1. but he wants the type whereas I'm trying to build a type out of my object) 获取按对象值类型过滤的对象键的联合类型(基本上与 1 相同。但他想要该type而我正试图我的对象中构建一个类型)
  3. Get keys of union of objects in TypeScript (Looks good but he also got a type...) 在 TypeScript 中获取对象联合的键(看起来不错,但他也有一个类型......)
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM