gpt4 book ai didi

typescript - TS : how to get constant Array element type

转载 作者:行者123 更新时间:2023-12-03 23:28:20 24 4
gpt4 key购买 nike

我将 TS 3.4.5 与 const 断言一起使用。如何检索声明的常量数组变量的元素类型?

export type GetArrayElementType<T extends Array<any>> = T extends (infer U)[] ? U : never;

export const MyConstArray = [
'item1',
'item2',
'item3',
] as const;

export type MyConstArrayItem = GetArrayElementType<typeof MyConstArray>;

我想有作为输出:
export type MyConstArrayItem = "item1" | "item2" | "item3"

我不完全确定如何提取项目的类型信息,因为由于 const 断言,我的数组不再是数组类型,而是一个常量元组,因此无法对其应用 GetArrayElementType

最佳答案

如果你想使用条件类型,你必须记住 as const 生成只读数组。所以这应该像你期望的那样工作:

export type GetArrayElementType<T extends readonly any[]> = T extends readonly (infer U)[] ? U : never;

export const MyConstArray = [
'item1',
'item2',
'item3',
'item4',
] as const;

export type MyConstArrayItem = GetArrayElementType<typeof MyConstArray>;

但更简单的解决方案是不使用条件类型。类型索引查询在这里效果更好:
export const MyConstArray = [
'item1',
'item2',
'item3',
'item4',
] as const;

export type MyConstArrayItem = typeof MyConstArray[number];

关于typescript - TS : how to get constant Array element type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56113411/

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