首页 > 解决方案 > 在 Typescript 中将元组类型转换为类型数组

问题描述

我正在尝试在香草打字稿中复制 Angular 的依赖注入行为。我的方法是将构造函数的参数类型作为元组类型获取,将其转换为类型数组,然后查看字典对象或数组并从该结构中获取其类型与数组位置中的类型匹配的对象。

在下面的代码中,我定义了一个测试类,其中构造函数采用苹果和橙子。在类定义下方,我可以将每个参数的类型转换为一个名为“TestClassParameters”的元组类型。

有什么方法可以将这种类型: [apple,orange] 转换为数组对象 => [typeof apple,typeof orrange]?

class Apple {}
class Orange { }

class TestClass {

    private apple : Apple;
    private orange: Orange;

    constructor(private apple: Apple, private orange: Orange) {}
}

type TestClassParameters = ConstructorParameters<typeof TestClass>;

标签: typescript

解决方案


推荐阅读