【问题标题】:Derive Type from Array Typescript从数组 Typescript 派生类型
【发布时间】:2021-12-15 11:35:22
【问题描述】:

我有一个数组

const frequencyOptions = ['Daily', 'Weekly', 'Monthly'];

我需要将 Typescript Type 设置为另一个数组,该数组只能包含选项数组中的值,例如

let frequencyValues = ['Daily', 'Weekly'] // can be any combination of options array

【问题讨论】:

  • 你没有提到你的问题是什么。
  • 我需要设置 values 数组的 typescript 类型,使其只能接受仅在 frequencyOptions 数组中可用的值。
  • 您控制选项数组的创建吗? frequencyOptions
  • @AlekseyL。是的,frequencyOptions 数组大部分是常量/静态

标签: javascript arrays typescript types


【解决方案1】:

如果您要控制选项数组的创建,您可以:

const frequencyOptions = ['Daily', 'Weekly', 'Monthly'] as const;
type Option = typeof frequencyOptions[number]; // "Daily" | "Weekly" | "Monthly"

let frequencyValues: Option[] = ['Daily', 'Weekly'];

// Expect error
frequencyValues = ['foo'] // Type '"foo"' is not assignable to type '"Daily" | "Weekly" | "Monthly"'.

Playground


as constprevents literal types wideningstring,然后我们query tuple item type

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 2010-10-20
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 2016-03-27
    • 1970-01-01
    • 2011-10-09
    相关资源
    最近更新 更多