【问题标题】:TS define type to equal one of values of typed arrayTS 将类型定义为等于类型化数组的值之一
【发布时间】:2023-03-16 14:34:01
【问题描述】:

假设我可以访问这样定义的类型 Keys

type Keys = ('AA' | 'BB' | 'CC')[]
  1. 如何创建一个新类型Key,使用类型Keys,使这个新类型等于:
type Key = 'AA' | 'BB' | 'CC'

请注意,我不能从字面上指定允许的值(AABB 等),我只有 Keys 类型可供使用。

【问题讨论】:

    标签: typescript types typing


    【解决方案1】:

    您可以使用indexed type query

    type Keys = ('AA' | 'BB' | 'CC')[]
    type Key = Keys[number]
    

    Playground Link

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多