在 TypeScript 中,类型转换主要分为 类型断言(Type Assertion)、类型守卫(Type Guard) 和 类型兼容转换 三种方式。以下是详细分类和示例:
一、类型断言(Type Assertion)
强制编译器将值视为特定类型,不改变运行时行为。
1. 尖括号语法
let value: any = "hello";
let length: number = (<string>value).length;
2. as 语法(更推荐,JSX 中必须使用)
let value: any = "hello";
let length: number = (value as string).length;
3. 非空断言(Non-null Assertion)
断言值不为 null
或 undefined
:
function printLength(str: string | null) {console.log((str!).length); // 断言 str 不为 null
}
二、类型守卫(Type Guard)
在运行时检查类型,缩小类型范围。
1. typeof 守卫
function add(a: number | string, b: number | string): number {if (typeof a === "number" && typeof b === "number") {return a + b; // a 和 b 被缩小为 number}return Number(a) + Number(b);
}
2. instanceof 守卫
class Animal { speak() {} }
class Dog extends Animal { bark() {} }function printPet(pet: Animal) {if (pet instanceof Dog) {pet.bark(); // pet 被缩小为 Dog}
}
3. 自定义类型守卫
interface Fish { swim: () => void }
interface Bird { fly: () => void }function isFish(pet: Fish | Bird): pet is Fish {return (pet as Fish).swim !== undefined;
}function move(pet: Fish | Bird) {if (isFish(pet)) {pet.swim(); // 类型为 Fish} else {pet.fly(); // 类型为 Bird}
}
三、类型兼容转换
基于类型结构的隐式转换(无需断言)。
1. 子类型赋值给父类型
interface Animal { name: string }
interface Dog extends Animal { breed: string }let dog: Dog = { name: "Buddy", breed: "Labrador" };
let animal: Animal = dog; // 合法:Dog 是 Animal 的子类型
2. 联合类型转换
let value: string | number = "hello";
let str: string = value as string; // 断言为 string
四、类型转换工具类型
1. typeof
获取值的类型:
const person = { name: "Alice", age: 30 };
type PersonType = typeof person; // { name: string; age: number }
2. keyof
获取类型的所有属性名:
type PersonKeys = keyof typeof person; // "name" | "age"
3. 类型映射
type ReadonlyPerson = Readonly<typeof person>; // 所有属性变为只读
五、运行时类型转换
实际修改值的类型(与 TypeScript 类型系统无关)。
1. 转字符串
String(123); // "123"
JSON.stringify({}); // "{}"
2. 转数字
Number("42"); // 42
parseInt("10px"); // 10
+"5"; // 5(一元加号)
3. 转布尔值
Boolean(0); // false
!!null; // false(双重否定)
六、常见陷阱与最佳实践
-
过度使用断言
- 避免使用
as any
绕过类型检查,优先使用类型守卫。
- 避免使用
-
类型守卫与断言的区别
- 类型守卫:运行时检查,真正缩小类型范围。
- 类型断言:仅告知编译器类型,不验证值的实际类型。
-
使用类型谓词(Type Predicate)
function isString(value: any): value is string {return typeof value === "string"; }
总结
场景 | 方法 | 示例 |
---|---|---|
强制类型转换(编译时) | 类型断言(as 或 <>) | (value as string).length |
运行时类型检查 | 类型守卫(typeof/instanceof) | if (typeof x === 'number') { ... } |
获取已有类型 | typeof | type T = typeof obj |
转换值的实际类型 | String()/Number()/Boolean() | Number("42") |
泛型约束 | extends | function identity<T extends string>(x: T) |
合理使用这些工具,可以让你的 TypeScript 代码既安全又灵活。