【问题标题】:Declare union type from a values of array [duplicate]从数组的值声明联合类型
【发布时间】:2022-10-07 22:18:09
【问题描述】:
export const files = ['a', 'b', 'c']

export type File = 'a' | 'b' | 'c'

如何在不重复 'a', 'b', 'c' 之类的值的情况下声明此文件类型。

【问题讨论】:

标签: typescript


【解决方案1】:

您可以使用typeofnumber 作为索引语法。请注意,数组定义中需要 as const

export const files = ['a', 'b', 'c'] as const;
export type File = typeof files[number];

Typescript Playground

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-20
    • 2021-04-11
    • 1970-01-01
    • 2017-12-28
    • 2012-07-18
    相关资源
    最近更新 更多