typescript - 映射`ConstructorParameters` 元组到对象类型
问题描述
我想知道是否有任何方法可以映射ConstructorParameters<T>
到一个对象,其中每个键是参数名称,键是参数的类型。
我的意思是,鉴于:
class User {
public id: number;
constructor(
public readonly name: string,
public readonly surname: string,
) {}
get fullname(): string { ... }
public isAdmin(): boolean { ... }
}
随着ConstructorParameters<typeof User>
我得到类型[name: string, surname: string]
。也许这可以映射到以下类型{ name: string, surname: string }
?请注意,类型应该省略: id
, fullname
&isAdmin
因为它们不存在于构造函数中。
我见过https://stackoverflow.com/a/49062616这是一个非常酷的解决方案,但它与构造函数中不存在的 getter 和公共属性中断。
解决方案
我不这么认为。函数参数的“名称”实际上在函数上下文之外没有任何意义。例如,您可以这样做:
type FuncType = (foo: string) => void;
const MyFunc: FuncType = (bar) => {
return bar;
}
foo
and的“名称”bar
根本不匹配,但顺序和类型匹配,这才是真正重要的。可能类似于如何解构数组并为项目指定任意名称;数组中的项目没有以开头的名称:
const array = [1, 2, 3];
const [one, two, three] = array;
您可能得到的最接近的方法是将构造函数的顺序和类型作为对象获取,但我不确定这会有什么用:
type ConstructorParametersIndices<T extends new (...args: any) => any> =
T extends new (...args: infer P) => any ? {[K in keyof P]: K} : never;
type A = ConstructorParameters<typeof User>;
// [name: string, surname: string]
type B = ConstructorParametersIndices<typeof User>;
// [name: "0", surname: "1"]
type C = {[P in B[number] as P]: A[P]};
/* {
* 0: string;
* 1: string;
/* }
推荐阅读
- posix - 可以将使用 boost 库在传统软件堆栈中编写的应用程序移植到自适应 AUTOSAR 堆栈中吗
- multithreading - Express js 多线程
- c# - 提取文件头签名,因为它在 ASP.NET Core 中直接流式传输到磁盘
- javascript - 使用“Date.prototype.toISOString”时可以去掉“.000Z”吗?
- r - 从包含列中的数字和字母的字符串中删除数字字符(在R中)
- crystal-reports - 将 sap b1 中标准选择中没有值的字段传递给水晶报告
- python - 为什么 pyinstaller 创建的可执行文件不起作用?
- javascript - 如何创建用于在字符串中查找电子邮件地址的 JavaScript 正则表达式?
- postgresql - 从 AIX Oracle 到 Postgresql 的 DBLink
- signalr - Signalr Hub 中的后台任务