【发布时间】: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