【问题标题】:TS: how to get constant Array element typeTS:如何获取常量数组元素类型
【发布时间】:2019-09-30 11:26:44
【问题描述】:

我正在使用带有 const 断言的 TS 3.4.5。如何检索声明的常量数组变量的元素类型?

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 不能应用于它.

【问题讨论】:

标签: typescript


【解决方案1】:

如果你想使用条件类型,你必须记住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];

【讨论】:

  • 谢谢,是的,刚刚在另一个 SO 问题上发现了,这就是我要找的 ;)
【解决方案2】:

可以通过以下方式轻松完成:

type MyConstArrayItem = typeof MyConstArray[number]

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-25
  • 2016-03-30
  • 2018-07-20
  • 2013-10-28
  • 2019-06-15
相关资源
最近更新 更多