个人技术分享

概述

  • 在TypeScript中,利用泛型和类型推断,我们可以编写出既灵活又安全的代码
  • 特别是在处理类和其实例化过程中,这些特性显得尤为重要
  • 我们着重关注构造函数参数(constructor parameters)的类型处理
  • 以及如何利用泛型工厂函数来创建类的实例
  • 构造函数是面向对象编程中初始化对象状态的核心手段
  • 在TypeScript中,通过为构造函数及其参数添加类型注解
  • 可以确保在创建对象时遵循预定义的类型规则,从而提高程序的健壮性

应用示例

// 定义一个简单的类  
class TestClass {
    public name: string;
    public classno: number;
  
    constructor(name: string, classno: number) {
        this.name = name;
        this.classno = classno;
    }
  
    greet() {  
        console.log(`Hello, my name is ${this.name} and I'm in class ${this.classno}.`);  
    }  
}  
  
// 定义构造函数类型和构造函数参数类型  
type Constructor<T> = new (...args: any[]) => T;  
type ConstructorParametersType<T extends Constructor<any>> = T extends new (...args: infer P) => any ? P : never;  
  
// 泛型工厂函数  
function createInstance<T>(constructor: Constructor<T>, ...args: ConstructorParametersType<Constructor<T>>): T {  
    return new constructor(...args);  
}  
  
// 使用泛型工厂函数创建TestClass的实例并调用其方法  
const instance = createInstance(TestClass, "Alice", 123);  
instance.greet(); // 输出:Hello, my name is Alice and I'm in class 123.

1 ) ConstructorParametersType

  • TypeScript提供了ConstructorParameters内置类型
  • 它能够自动提取构造函数的参数类型
  • 但为了深入理解其原理,我们先自定义一个ConstructorParametersType
    type ConstructorParametersType<T extends new (...args: any[]) => any>
      = T extends new (...args: infer P) => any ? P : never;
    
  • 这段代码展示了TypeScript的条件类型与infer关键字的强大功能
  • 它定义了一个泛型类型T,要求T是一个构造函数类型
  • 即接受任意数量参数并返回某个类型的构造函数
  • 通过infer P,我们可以从T中推断出实际的参数类型数组P,最终作为输出类型
  • 如果T不符合预期构造函数类型,则默认返回never,确保类型安全

2 ) 泛型工厂函数:动态实例化的桥梁

  • 接下来,我们利用ConstructorParametersType来实现一个高度灵活的工厂函数createInstance

  • 此函数接收两个泛型参数:T代表要实例化的类的类型,而CP约束为对应的构造函数类型

  • 函数体内的类型声明 ...args: ConstructorParametersType<CP>保证了传入的参数与构造函数期望的参数类型完全匹配

    function createInstance<T, CP extends new (...args: any[]) => any>(
      constructor: CP,
      ...args: ConstructorParametersType<CP>
    ): InstanceType<CP> {
      return new constructor(...args);
    }
    
  • 这里, InstanceType<CP> 是另一个TypeScript内置类型

  • 用于从构造函数类型推断出实例类型,确保返回值具有正确的类型

3 ) 总结

  • 在这个示例中,我首先定义了一个 TestClass
  • 它有一个构造函数接受 nameclassno 作为参数,并有一个eat方法用于打印学生信息
  • 之后,定义了一个工厂函数 createInstance
  • 它使用了TypeScript的内置类型 ConstructorParameters<T>来获取构造函数的参数类型
  • 以及InstanceType<T>来表示构造函数实例的类型,这样就不需要手动定义ConstructorParametersType
  • 通过这种方式,createInstance函数变得更加简洁且直接,同时仍然保持了类型安全,确保传入的参数类型与构造函数参数类型严格匹配
  • 最后,通过调用createInstance函数创建了TestClass的一个实例并调用了eat方法来验证功能