TypeScript中的infer占位符

87 阅读1分钟

(1) infer 出现在extends 条件语句后的函数类型的参数位置上

interface Customer {
    custname:string
    buymoney:number
}
type custFuncType = (cust:Customer) => string
type inferType<T> = T extends (params:infer P)=> any?P:T
type inferResultType = inferType<custFuncType>

解析 type inferType<(cust:Customer) => string> = (cust:Customer) => string extends (params:infer P)=> any?P:T (cust:Customer) => string 和 (params:infer P)=> any 匹配 P替换为Customer 结果为true 返回 Customer

(2) infer 出现在extends 条件语句后的函数类型的返回值类型上

interface Customer {
    custname:string
    buymoney:number
}
type custFuncType = (cust:Customer) => string
type inferType<T> = T extends (params:any)=> infer P ? P:T
type inferResultType = inferType<custFuncType>

解析 type inferType<(cust:Customer) => string> = (cust:Customer) => string extends (params:any)=> infer P ? P:T (cust:Customer) => string 和 (params:any)=> infer P 匹配 P替换为string 结果为true 返回 string

(3) infer 出现在类型的泛型具体化类型上

type Elementofo<T> = T extends Set<infer E> ? E : never
let result:Elementofo<Set<string>>

解析 Elementofo<Set> ===>> Set extends Set E 得到 string 类型 返回结果 string

infer的使用场景

class TestClass {
    public name:string
    public classno:number
    constructor(name:string,classno:number){
        this.name = name
        this.classno = classno
    }
    eat(){
        console.log("姓名为:"+this.name+" 班级:"+this.classno)
    }
}
type ConstructorParametersType<T> = T extends new (...args: infer P) => any ? P : never

type Constructor<T> = new (...args:any[]) => T

//let constructor:ConstructorParametersType<typeof TestClass> //[name: string, classno: number] 

function createInstance<T,D>(constructor:Constructor<T>,...args:ConstructorParametersType<D>){
    return new constructor(args[0],args[1])
}

createInstance<TestClass,typeof TestClass>(TestClass,"张三",18).eat()