ConstructorParameters

ConstructorParameters 是 TypeScript 中的一个工具类型(utility type),它用于获取构造函数参数的类型。这个工具类型可以用来提取类构造函数的所有参数类型的元组。

用法

ConstructorParameters 的基本语法如下:

复制代码
type ConstructorParameters<T> = T extends new (...args: infer P) => any ? P : never;
  • T 是一个构造函数类型。
  • infer P 用于推断构造函数的参数类型,并将它们存储在 P 中。
  • 如果 T 不是一个构造函数,那么结果将是 never

示例

假设你有一个类 Person,它的构造函数接受两个参数:nameage

复制代码
class Person {
  constructor(public name: string, public age: number) {}
}

你可以使用 ConstructorParameters 来提取 Person 类构造函数的参数类型:

复制代码
type PersonParams = ConstructorParameters<typeof Person>;

// PersonParams 的类型是 [string, number]

具体应用场景

1. 创建工厂函数

假设你想创建一个工厂函数来生成 Person 实例,但你希望确保工厂函数的参数与 Person 构造函数的参数一致。

复制代码
function createPerson(...args: ConstructorParameters<typeof Person>) {
  return new Person(...args);
}

const person = createPerson("Alice", 30); // 正确
// const person2 = createPerson("Bob"); // 编译错误,缺少参数
2. 泛型工厂函数

如果你有多个类,并且希望为这些类创建通用的工厂函数,你可以使用泛型和 ConstructorParameters

复制代码
class Employee {
  constructor(public name: string, public department: string) {}
}

function createInstance<T>(ctor: new (...args: any[]) => T, ...args: ConstructorParameters<typeof ctor>): T {
  return new ctor(...args);
}

const employee = createInstance(Employee, "John Doe", "HR");
const person = createInstance(Person, "Jane Doe", 25);

console.log(employee); // Employee { name: 'John Doe', department: 'HR' }
console.log(person);   // Person { name: 'Jane Doe', age: 25 }

在这个例子中,createInstance 函数接受一个构造函数 ctor 和任意数量的参数 argsargs 的类型由 ConstructorParameters<typeof ctor> 确定,这样可以确保传入的参数与构造函数的参数类型匹配。

3. 参数类型检查

你还可以使用 ConstructorParameters 来进行参数类型检查,确保传递给某个函数或方法的参数与预期的构造函数参数类型一致。

复制代码
function checkPersonParams(...params: ConstructorParameters<typeof Person>) {
  if (typeof params[0] !== 'string') {
    throw new Error('First parameter must be a string');
  }
  if (typeof params[1] !== 'number') {
    throw new Error('Second parameter must be a number');
  }
}

try {
  checkPersonParams("Alice", 30); // 通过
  checkPersonParams(42, "Alice"); // 抛出错误
} catch (error) {
  console.error(error.message);
}

总结

ConstructorParameters 是一个非常有用的工具类型,可以帮助你在 TypeScript 中提取和使用构造函数的参数类型。这使得代码更加类型安全,减少了手动维护类型定义的工作量。通过结合泛型和其他 TypeScript 特性,你可以编写出更加灵活和健壮的代码。

相关推荐
伍哥的传说40 分钟前
鸿蒙系统(HarmonyOS)应用开发之手势锁屏密码锁(PatternLock)
前端·华为·前端框架·harmonyos·鸿蒙
yugi98783842 分钟前
前端跨域问题解决Access to XMLHttpRequest at xxx from has been blocked by CORS policy
前端
浪裡遊1 小时前
Sass详解:功能特性、常用方法与最佳实践
开发语言·前端·javascript·css·vue.js·rust·sass
旧曲重听12 小时前
最快实现的前端灰度方案
前端·程序人生·状态模式
默默coding的程序猿2 小时前
3.前端和后端参数不一致,后端接不到数据的解决方案
java·前端·spring·ssm·springboot·idea·springcloud
夏梦春蝉2 小时前
ES6从入门到精通:常用知识点
前端·javascript·es6
归于尽2 小时前
useEffect玩转React Hooks生命周期
前端·react.js
G等你下课2 小时前
React useEffect 详解与运用
前端·react.js
我想说一句2 小时前
当饼干遇上代码:一场HTTP与Cookie的奇幻漂流 🍪🌊
前端·javascript
funnycoffee1232 小时前
Huawei 6730 Switch software upgrade example版本升级
java·前端·华为