模式切换
联合类型
在 TypeScript 中,联合类型(Union Types)允许一个变量、函数参数或函数返回值取几种不同的类型之一。这是通过使用 |
符号分隔每个类型来定义的。
在下面例子中,value 变量被定义为一个联合类型,它可以是 string 或 number。这意味着我们可以给 value 赋一个字符串或一个数字,但不能赋一个其他类型的值。 同样,printValue 函数接受一个 string | number 类型的参数。这意味着它可以接受一个字符串或一个数字作为参数。
当处理联合类型的变量时,你可能需要使用类型断言或条件语句来确保你正在访问的类型是正确的,以避免类型错误。
typescript
// 定义一个变量,它可以是一个字符串或数字
let value: string | number;
// 可以给这个变量赋一个字符串或数字
value = 'hello';
value = 42;
// 不能给这个变量赋一个既不是字符串也不是数字的值
value = true; // 错误:类型 'boolean' 不能赋值给类型 'string | number'
// 函数可以接受不同类型的参数
function printValue(value: string | number) {
console.log(value);
}
printValue('hello'); // 输出 "hello"
printValue(42); // 输出 42
// 不能传递一个既不是字符串也不是数字的参数
printValue(true); // 错误:参数类型 'boolean' 不能赋值给参数 'value' 的类型 'string | number'
// 使用类型断言来明确告诉 TypeScript 编译器变量的实际类型
let strValue: string | number = 'hello';
let strLength: number = (strValue as string).length; // 断言 strValue 是字符串
// 使用条件语句来确保类型安全
if (typeof strValue === 'string') {
let strLength: number = strValue.length;
} else {
let numValue: number = strValue;
}