
typescript 函数中类型判断
在 typescript 中,定义了多个接口时,在函数体中需要判断参数的特定类型才能进行相应的处理。为了实现此功能,有几种方法可以考虑:
1. 谓词函数
这种方法需要手动编写一个谓词函数来检查特定类型。例如,判断一个对象是否为 person,可以写出如下函数:
function isperson(o: unknown): o is person {
// ... 具体检查代码
}然后在函数体中使用:
if (isperson(some)) {
// ... 处理 person 类型
}2. io-ts 库
io-ts 库提供了一种更方便的方式来定义和验证类型的工具。其使用如下:
import * as t from 'io-ts';
const user = t.type({
name: t.string,
age: t.number
});
function test(some: user | animal) {
if (user.is(some)) {
// ... 处理 user 类型
}
}3. 类和 实例类型检查
typescript 中的类既是类型,也是值。因此,可以创建类实例并使用 instanceof 操作符检查类型,如下:
class Person {
name: string;
age: number;
// ...
}
class Animal {
food: string;
kind: string;
// ...
}
function test(some: Person | Animal) {
if (some instanceof Person) {
// ... 处理 Person 类型
}
}










