【问题标题】:Saying that a variable is a member of an array in typescript [duplicate]说变量是打字稿中数组的成员[重复]
【发布时间】:2021-06-30 09:26:24
【问题描述】:

假设我有一个数组const a = ['apple', 'orange']

基本上,我想将其转换为:

type MyType = 'apple' | 'orange';

我不知道 Typescript 是否可以做到这一点。我搜索了很多,但没有找到方法。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    如果您只写const a = ['apple', 'orange'],编译器将推断a 的类型为string[],并且有关literal "apple""orange" 值的任何信息都将丢失。这是合理的默认行为,因为人们经常希望从字符串数组中添加/删除 string 值。但这对您的用例没有帮助;它太宽了。您希望编译器为 a 推断出更窄的类型。

    一种方法是使用const assertion

    const a = ['apple', 'orange'] as const;
    // const a: readonly ["apple", "orange"]
    

    现在编译器推断a 是文字字符串类型"apple""orange"readonly tuple,按此顺序。


    此时你有足够的信息来计算MyType

    type MyType = (typeof a)[number];
    // type MyType = "apple" | "orange"
    

    这是使用typeof type operator 查找a 的类型(即readonly ["apple", "orange"]),然后使用number 索引对其执行indexed access。由于(typeof a) 是一个数组类型,那么如果您使用numbera 进行索引,您将获得"apple""orange" 文字类型的值。因此,(typeof a)[number]"apple" | "orange"

    Playground link to code

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-02
      • 2014-10-13
      • 2018-03-05
      • 2021-11-10
      • 2017-12-19
      • 2020-06-29
      • 2017-06-10
      • 1970-01-01
      相关资源
      最近更新 更多