简体   繁体   English

Typescript - 如何获取类型化数组?

[英]Typescript - How Do I Get A Typed Array?

My Sample use case.我的示例用例。

type someEnum = 'a' | 'b';

const someObj: { [K in someEnum]: string } = {
    a: 'a',
    b: 'b',
};

const a: Array<someEnum> = ['a', 'b'];

// In Future update someEnum

type someEnum = 'a' | 'b' | 'c';

// Gives an error;

// Property 'c' is missing in type '{ a: string; b: string; }' 
// but required in type '{ a: string; b: string; c: string; }'.

const someObj: { [K in someEnum]: string } = {
    a: 'a',
    b: 'b',
};

// No error;
const a: Array<someEnum> = ['a', 'b'];

// Is There someThing like;

// const typedArray: [K in someEnum]

It would be really cool to have such a feature;拥有这样的功能真的很酷; Is there some functionality to achieve the same.是否有一些功能可以实现相同的功能。 Thanks in advance.提前致谢。

It's tempting to use some workaround to get tuple to union, please don't use it .使用一些变通方法将元组合并是很诱人的,请不要使用它

You can work around this issue in several ways, the simplest way is if the enum is under your control, start from the array instead of the enum:您可以通过多种方式解决此问题,最简单的方法是如果枚举在您的控制之下,则从数组而不是枚举开始:

const allPosibilitieForSomeEnum = ['a',  'b' , 'c'] as const
type someEnum = typeof allPosibilitieForSomeEnum[number];

You could use an object instead and use keys to get the keys.您可以改用对象并使用keys来获取密钥。

Or you could use a function that validates that all memebers are present:或者您可以使用验证所有成员都存在的函数:

type someEnum = 'a' | 'b' | "c";

function checkEnum<TEnum>() {
    return function <TActual extends TEnum[]>(...p: TActual & ([TEnum] extends [TActual[number]] ? {} : {
        error: ["Array does not contain all members, expected: ", TEnum, "found:", TActual[number]]
    })) {
        return p
    }
}

const someObj =  checkEnum<someEnum>()("a", "b", "c") 
const someObj2 =  checkEnum<someEnum>()("a", "b") ///  Property 'error' is missing in type '["a", "b"]' but required in type '{ error: ["Array does not contain all members, expected: ", someEnum, "found:", "a" | "b"]; }'.

You want to create a tuple out of a union type.您想根据联合类型创建一个元组。 That is indeed possible but a little bit more complex.这确实是可能的,但有点复杂。 There is also an issue in the TypeScript Github repository that adresses this. TypeScript Github 存储库中还有一个问题可以解决这个问题。

One of the answers there seems to work pretty well.那里的答案之一似乎工作得很好。 Here the example in TypeScript Playground .这是TypeScript Playground 中的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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