ts 类型缩小的方式有哪些

更新时间:2023-09-08 21:32
TypeScript 中的类型缩小(Type Narrowing)是一种能够提高类型安全性的技巧。它可以让 TypeScript 的编译器更加明确变量或表达式的类型,从而减少潜在的类型错误。
以下是 TypeScript 中一些常见的类型缩小方式:
使用类型保护函数(Type Guard): TypeScript 中的类型保护函数是一种特殊的函数,它们执行运行时检查并返回一个类型谓语,告知 TypeScript 编译器变量或参数的更具体的类型。
 
function isString(test: any): test is string{
    return typeof test === "string";
}

function example(foo: any){
    if (isString(foo)) {
        console.log("It is a string: " + foo);
        console.log(foo.length); // string function
    }
}
使用 typeof 操作符: typeof 操作符可以检查变量或表达式的类型,并返回一个表示类型的字符串
let item: string | number;

if (typeof item === 'string') {
    // 在这个代码块中,TypeScript 知道 'item' 是一个 string 类型
    console.log(item.trim());
}
使用 instanceof 操作符: instanceof 操作符可以检查一个对象是否是某个类的实例。
class MyClass {}

const instance = new MyClass();

if (instance instanceof MyClass) {
    // TypeScript 知道 'instance' 是 MyClass 类型
}
使用 in 操作符: in 操作符用于检查对象是否包含某个特定属性。
type A = { a: number };
type B = { b: string };

function doSomething(value: A | B) {
  if ('a' in value) {
    // 在这里,TypeScript 知道 'value' 是类型 'A'
    console.log(value.a);
  }
}
使用字面量类型缩小:
type Foo = {
  kind: 'foo'; 
  foo: number;
}

type Bar = {
  kind: 'bar';
  bar: number;
}

type Union = Foo | Bar;

function example(arg: Union) {
  if (arg.kind === 'foo') {
    console.log(arg.foo); 
  } else {
    console.log(arg.bar); 
  }
}
上述每种类型缩小都有其适用场景,根据具体需求和上下文选择合适的类型缩小策略能够提高代码的类型安全性和可读性。