【问题标题】:How to exhaustive check the elements in an array in typescript?如何在打字稿中详尽检查数组中的元素?
【发布时间】:2022-10-12 22:10:39
【问题描述】:

鉴于我可以使用Record 让我不会忘记在对象中键入所有选项

type Country = "uk" | "france" | "india";

export const data: Record<Country, boolean> = {
  uk: true,
  france: true,
  // complains that india is not present, excellent!
};

我怎样才能让它以同样的方式抱怨数组?

export const data = [
  {value: "uk"},
  {value: "france"},
  // how to make typescript complain here that I forgot to add {value: "india"}?
];

【问题讨论】:

  • 没有合适的类型可以为您进行此验证。您可以创建所有可能的数组组合的联合,或者只满足一种特定的元素顺序。或者,您可以使用将数组传递给的通用函数。泛型函数可以使用推理和泛型类型在编译时进行此检查。

标签: typescript


【解决方案1】:

我正在使用库中的一些实用程序功能,但不使用它完全可以实现。实际上,我从堆栈溢出中得到了一些帮助,以便提出这个解决方案哈哈……感谢caTSRelated question

import { List, Union } from "ts-toolbelt";

type GetData<TCountries extends string[]> = List.Length<TCountries> extends 0
  ? []
  : List.Append<GetData<List.Pop<TCountries>>, {
    value: List.Last<TCountries>
  }>;

export const data : GetData<Union.ListOf<Country>> = [
  {value: "uk"},
  {value: "france"},
  // how to make typescript complain here that I forgot to add {value: "india"}?
];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-26
    • 2018-09-28
    • 2021-09-13
    • 2021-04-03
    • 1970-01-01
    • 2018-10-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多