TS学习笔记

197 阅读1分钟

infer

表示在 extends 条件语句中待推断的类型变量。

type ParamType<T>  =  T extends (...arg: P) ? P : T

// 经典例子 ReturnType
//用于提取函数类型的返回值类型:
type ReturnType<T> = T extends (...args: any[]) => infer P ? P : any;

// 用于提取构造函数中参数(实例)类型:
type ConstructorParameters<T extends new (...arg: any[]) => any> = T extends new (...arg: infer P) => any ? P :never

type ConstructorParameters1<T extends new (...arg: any[]) => any> = T extends new (...arg: infer P) => any ? P :never

class TestClass {
    constructor( public name: string, public age: number){

    }
}
type params =  ConstructorParameters1<typeof TestClass> // [string,number]
const test:params = ['123',123]

is

使用 is 来判定值的类型

function isAxiosError (error: any): error is AxiosError {
  return error.isAxiosError
}

// 防止类型报错
if (isAxiosError(err)) {
  code = `Axios-${err.code}`
}