在TypeScript中,你可以使用多种方法来检查值的类型。以下是一些常见的方法:
typeof
操作符typeof
操作符可以用来获取一个值的类型,并且可以与类型断言结合使用来检查类型。
function printInfo(value: unknown) {
if (typeof value === 'string') {
console.log('It is a string:', value);
} else if (typeof value === 'number') {
console.log('It is a number:', value);
} else {
console.log('Unknown type');
}
}
instanceof
操作符instanceof
操作符用于检查一个对象是否是某个类的实例。
class Animal {}
class Dog extends Animal {}
function checkAnimal(animal: any) {
if (animal instanceof Dog) {
console.log('It is a dog');
} else if (animal instanceof Animal) {
console.log('It is an animal');
} else {
console.log('It is not an animal');
}
}
类型守卫是一种特殊的函数,它可以缩小变量的类型范围。
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();
} else {
pet.fly();
}
}
in
操作符in
操作符可以用来检查对象是否具有某个属性,从而推断类型。
interface Square {
kind: 'square';
size: number;
}
interface Rectangle {
kind: 'rectangle';
width: number;
height: number;
}
type Shape = Square | Rectangle;
function area(s: Shape) {
if ('size' in s) {
return s.size * s.size; // s is Square here
} else {
return s.width * s.height; // s is Rectangle here
}
}
类型断言允许你告诉编译器某个值的具体类型。
function assertIsString(value: any): asserts value is string {
if (typeof value !== 'string') {
throw new Error('Value is not a string');
}
}
function processString(value: unknown) {
assertIsString(value);
console.log(value.toUpperCase());
}
通过上述方法,你可以在TypeScript中有效地检查和处理不同类型的值。
领取专属 10元无门槛券
手把手带您无忧上云