返回
TypeScript 如何在不同的类型之间转换?
前端
2023-09-01 06:29:40
TypeScript 类型转换
TypeScript 提供了许多内置类型,可以满足大多数场景的需求。但有时,我们可能需要将一种类型转换为另一种类型。TypeScript 提供了多种方法来实现类型转换,包括:
- 显式类型转换 :使用
as
将一种类型显式转换为另一种类型。 - 接口转换 :使用
implements
关键字将一个类型转换为实现某个接口的类型。 - 类转换 :使用
extends
关键字将一个类型转换为继承自某个类的类型。 - 泛型 :使用类型参数来定义一个类型,该类型可以接受不同类型的参数。
- 映射类型 :使用
{}
和keyof
来定义一个类型,该类型可以将一个类型的键映射到另一个类型的值。
类型转换示例
下面是一些类型转换的示例:
// 显式类型转换
let num: number = 10;
let str: string = num as string;
// 接口转换
interface Person {
name: string;
}
class Employee implements Person {
name: string;
salary: number;
}
let emp: Employee = new Employee();
let person: Person = emp;
// 类转换
class Animal {
name: string;
}
class Dog extends Animal {
bark() {
console.log("Woof!");
}
}
let dog: Dog = new Dog();
let animal: Animal = dog;
// 泛型
function identity<T>(x: T): T {
return x;
}
let n = identity<number>(10);
let s = identity<string>("Hello");
// 映射类型
type ReadonlyPerson = {
readonly [key in keyof Person]: Person[key];
};
let readonlyEmp: ReadonlyPerson = {
name: "John Doe",
};
// 这里readonlyEmp.name 是只读的
总结
TypeScript 提供了多种类型转换的方法,可以满足不同的场景需求。通过合理使用类型转换,可以提高代码的可读性、可维护性和可重用性。