我创建了一个类型
WithoutType
,其中我排除了枚举成员:
export enum MyEnum {
One = "one",
Two = "two",
Three = "three",
Zero = "zero",
}
export type WithoutType = Exclude<MyEnum, MyEnum.Zero>;
现在我需要检查某个 value 是否与
WithoutType
类型的联合值之一匹配。
我该怎么做?
要检查某个值是否与 JavaScript 中的 WithoutType 类型的联合值之一匹配,您可以创建一个使用 WithoutType 值来执行检查的函数。具体方法如下:
以下是实现此方法的方法:
第 1 步:定义枚举和类型
export enum MyEnum {
One = "one",
Two = "two",
Three = "three",
Zero = "zero",
}
export type WithoutType = Exclude<MyEnum, MyEnum.Zero>;
第 2 步:创建 JavaScript 函数来检查值
然后,创建一个 JavaScript 函数来检查 WithoutType 联合中是否存在给定值:
// Assuming you have this Enum and TypeScript type:
const MyEnum = {
One: "one",
Two: "two",
Three: "three",
Zero: "zero",
};
// This would be your TypeScript type WithoutType in JS:
const WithoutTypeValues = [
MyEnum.One,
MyEnum.Two,
MyEnum.Three,
];
// Function to check if a value is in WithoutType
function isWithoutType(value) {
return WithoutTypeValues.includes(value);
}
// Example usage:
console.log(isWithoutType("one")); // true
console.log(isWithoutType("zero")); // false
console.log(isWithoutType("two")); // true
console.log(isWithoutType("four")); // false
我认为这就是我的全部内容,只需按照这些步骤,您就可以使用 JavaScript 准确确定某个值是否对应于
WithoutType
类型中的任何联合值。
希望你能理解我的回答。如果有什么不明白的地方欢迎在下方评论。