我一直在尝试创建一个函数,其中函数的参数是由另外两个联合组成的一个联合。我想要它,以便根据传入参数的字符串,相应地触发一个不同的函数。就像这样:
type Type1 = "a" | "b" | "c";
type Type2 = "x" | "y" | "z";
function doSomething(param: Type1 | Type2) {
// if param is a part of the "Type1" union
functionForTypeOne();
}
doSomething("z");我在互联网和文档中搜索,我找不到一种方法来完成这个运行时类型检查。我找到了一些类型检查的“解决方案”,但它们都是为对象类型编写的,而不是字符串和联合。
在基本的javascript中,我可以创建一个const数组,并检查该字符串是否在数组中找到,如下所示:
const type1 = ["a", "b", "c"];
const type2 = ["x", "y", "z"];
function doSomething(param) {
if (type1.includes(param))
functionForTypeOne();
}在TypeScript中这样做是一种解决方案,但是由于我需要从这些consts创建联合,所以感觉效率很低,并且不允许我使用该语言的类型检查特性。我很好奇是否有人能找到我可能忽略的解决方案,或者这是我解决问题的唯一方法。
发布于 2022-08-25 03:40:36
您可以几乎自动地从元组构建联合,并使用类型保护谓词恢复类型安全性:
const type1 = ["a", "b", "c"] as const; // Assert as const to infer tuple instead of array string[]
const type2 = ["x", "y", "z"] as const;
// Automatically get union type from tuple values
type Type1 = typeof type1[number];
// ^? "a" | "b" | "c"
type Type2 = typeof type2[number];
// ^? "x" | "y" | "z"
// Type guard predicate
function isIn<T extends readonly string[]>(val: string, arr: T): val is T[number] {
return arr.includes(val);
}
function doSomething(param: Type1 | Type2) {
param
//^? "a" | "b" | "c" | "x" | "y" | "z"
if (isIn(param, type1)) {
param
//^? "a" | "b" | "c"
//functionForTypeOne();
}
}https://stackoverflow.com/questions/73481313
复制相似问题