【问题标题】:Array of const type, no more no less valuesconst 类型的数组,没有更多没有更少的值
【发布时间】:2021-09-05 08:52:14
【问题描述】:

我正在使用的库导出这样的类型:

type Pet = 'dog' | 'cat' | 'rat';

我现在想在我的 UI 中创建一个包含所有这些值的下拉菜单。我无法枚举此 const 类型。所以我想创建一个这些值的数组并键入它,这样它必须在类型 Pet 中的每个 const 中都有一个,但无法弄清楚。

我尝试了以下方法,但是当更多键添加到Pet 时不会导致错误。当我更新 lib 并且 lib 决定添加更多 const 时,我希望 typescript 在构建时失败。

type Pet = 'dog' | 'cat' | 'rat';

const pets: Pet[] = ['dog', 'dog']; // this should error as its missing "cat" and "rat". and also it has "dog" twice.

【问题讨论】:

    标签: typescript


    【解决方案1】:

    基于this 如果您使用TypeScript 4.1 或更高版本,您可以这样做:

    type UniqueArray<T> =
      T extends readonly [infer X, ...infer Rest]
        ? InArray<Rest, X> extends true
          ? ['Encountered value with duplicates:', X]
          : readonly [X, ...UniqueArray<Rest>]
        : T
    
    type InArray<T, X> =
      T extends readonly [X, ...infer _Rest]
        ? true
        : T extends readonly [X]
          ? true
          : T extends readonly [infer _, ...infer Rest]
            ? InArray<Rest, X>
            : false
    
    
    const data = ['dog', 'cat' , 'rat'] as const
    const uniqueData: UniqueArray<typeof data> = data
    
    const pets: UniqueArray <typeof data> = ['dog', 'dog']; // this should error as its missing "cat" and "rat". and also it has "dog" twice.
    

    Here 是工作代码。

    【讨论】:

    • 哇这真的很酷!谢谢你!
    • 但实际上我们可以让const datatype Pets = 'dog' | 'cat' | 'rat' 我试图确保数组中的每个键都存在于这种类型中。
    • 当我将其更改为:type Pet = 'dog' | 'cat' | 'rat' | 'mouse'; const data = ['dog', 'cat' , 'rat'] as Pet[];data 不包括"mouse" 时它不会出错
    • 你需要定义const变量
    • 该代码中重要的是 as const 。见this
    猜你喜欢
    • 2010-09-24
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-24
    • 1970-01-01
    相关资源
    最近更新 更多