TypeScript 是一种静态类型的 JavaScript 超集,它允许开发者为变量、函数参数和返回值指定类型。联合类型(Union Types)是 TypeScript 中的一种类型,表示一个值可以是几种类型之一。
联合类型使用竖线 |
分隔多个类型,表示一个值可以是这些类型中的任意一种。例如:
type StringOrNumber = string | number;
以下是一个返回预定义联合类型的函数的示例:
// 定义一个联合类型
type Result = string | number | boolean;
// 函数根据输入返回不同类型的值
function getResult(input: string): Result {
if (input === "string") {
return "This is a string";
} else if (input === "number") {
return 42;
} else if (input === "boolean") {
return true;
} else {
throw new Error("Invalid input");
}
}
// 使用函数
try {
console.log(getResult("string")); // 输出: This is a string
console.log(getResult("number")); // 输出: 42
console.log(getResult("boolean")); // 输出: true
console.log(getResult("unknown")); // 抛出错误: Invalid input
} catch (error) {
console.error(error.message);
}
原因:TypeScript 可能无法准确推断联合类型中的具体类型,导致在使用时出现类型错误。
解决方法:
function processResult(result: Result) {
if (typeof result === "string") {
console.log(result.toUpperCase()); // result 在这里是 string 类型
} else if (typeof result === "number") {
console.log(result.toFixed(2)); // result 在这里是 number 类型
} else if (typeof result === "boolean") {
console.log(result.toString()); // result 在这里是 boolean 类型
}
}
通过这种方式,可以确保在处理联合类型时,TypeScript 能够正确识别和使用具体的类型。
领取专属 10元无门槛券
手把手带您无忧上云