TypeScript 迭代字符串联合类型

NN_*_*NN_ 7 typescript

假设我有:

class A {
 f():void{}
 g():void{}
}
const a = new A();

type AFunctions = "f" | "g";
Run Code Online (Sandbox Code Playgroud)

我想迭代 AFunctions 并生成新函数。类似于映射类型,但具有实现,当然无需手动编写所有键。

伪代码

const b: A = {
 for F in AFunctions add function F() {
   return a[f]();
  }
}
Run Code Online (Sandbox Code Playgroud)

Tit*_*mir 3

Object.getOwnPropertyNames您可以使用和迭代类的属性Object.getPrototypeOf

function mapFunctions<T>(type: new (... params: any[])=> T) : { [P in keyof T] : ()=> void } {
    let mapped: { [name: string] : ()=> void } = {}

    let p = type.prototype;
    while(p !=  Object.prototype) {
        for (const prop of Object.getOwnPropertyNames(p)) {
            if(prop == 'constructor') continue;
            if(typeof p[prop] !== 'function') continue;

            mapped[prop] = ()=> {
                console.log(prop);
            }
        }
        p = Object.getPrototypeOf(p);
    }

    return <any>mapped;
}
class A {
    f(): void { }
    g(): void { }
}

class B extends A{
    h(): void { }
    i(): void { }
}
let ss = mapFunctions(B); // has functions f,g,h,i
Run Code Online (Sandbox Code Playgroud)

将函数的类型与原始对象上的函数结果联系起来更加困难, 2.8 中的条件类型及其关联的推理行为将让您深入了解返回类型和参数类型,但目前您只能使用完整的函数类型,例如{ [P in keyof T] : ()=> T[P] }(对于没有参数的函数,返回与原始函数具有相同签名的函数)或{ [P in keyof T] : (fn: T[P])=> void }(对于采用与原始函数具有相同签名的函数作为参数的函数)