gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:52 25 4
gpt4 key购买 nike

我的示例用例。

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]

如果有这样的功能,那真是太酷了;是否有一些功能可以实现相同的功能。提前致谢。

最佳答案

很容易使用一些变通方法来获得 tuple to union, please don't use it .

您可以通过多种方式解决此问题,最简单的方法是如果枚举在您的控制之下,则从数组而不是枚举开始:

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

您可以改用对象并使用 keys 获取 key 。

或者您可以使用验证所有成员都存在的函数:

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"]; }'.

关于Typescript - 如何获取类型化数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57323618/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com