gpt4 book ai didi

reflection - Typescript - 代表任何类的类型?

转载 作者:搜寻专家 更新时间:2023-10-30 20:37:30 27 4
gpt4 key购买 nike

我应该在 typescript 中使用什么类型来表示任何类?

我正在尝试编写一个函数,它接受一个类数组并返回一个具有不同顺序的数组。

function shuffle(classes: typeof Object[]) : typeof Object[] {
return ...;
}

class A { }
class B extends A { }
class C extends B { }
class D extends B { }
shuffle([A, B, C, D]);

Argument of type 'typeof A[]' is not assignable to parameter of type 'ObjectConstructor[]'.

然后我尝试了:

shuffle([typeof A, typeof B, typeof C, typeof D]);

error TS2345: Argument of type 'string[]' is not assignable to parameter of type 'ObjectConstructor[]'.Type 'string' is not assignable to type 'ObjectConstructor'.

什么是正确的方法?泛型?如何?这不起作用:

export function <T extends typeof Object> shuffle(classes: T[]) : T[]

这两者都不是:

export function <T extends Object> sortClassesBySpeciality(classes: typeof T[]) : typeof T[]

还有为什么 typeof (typeof A)"string"""+ typeof Afunction? 好的,明白了,typeof 有两种截然不同的含义上下文类型定义和表达式。

(最终目标是根据 Objectextends 级别对类进行排序。)

最佳答案

你应该避免在 typescript 中使用 Object 类型,你最好使用 any 作为 the docs say :

You might expect Object to play a similar role, as it does in other languages. But variables of type Object only allow you to assign any value to them - you can’t call arbitrary methods on them, even ones that actually exist

但是如果你想表示类,那么你需要有以下形式:

{ new (): CLASS_TYPE }

或者在你的情况下:

function shuffle(classes: Array<{ new (): any }>): Array<{ new (): any }> {
return [];
}

class A { }
class B extends A { }
class C extends B { }
class D extends B { }
shuffle([A, B, C, D]);

( code in playground )

如果您所有的类都基于父类(super class)(正如您的示例所暗示的那样),那么您可以简单地执行以下操作:

function shuffle(classes: Array<{ new (): A }>): Array<{ new (): A }> {
return [];
}

编辑

刚刚看到你想要

sort the classes by level of extends from Object

要回答这个问题:

function shuffle(classes: Array<{ new (): any }>): Array<{ new (): any }> {
return classes.sort((a, b) => getInheritanceLevel(a) - getInheritanceLevel(b));
}

function getInheritanceLevel(cls: { new (): any }): number {
let level = 0;

while (Object.getPrototypeOf(cls.prototype) !== Object.prototype) {
level++;
cls = Object.getPrototypeOf(cls.prototype).constructor;
}

return level;
}

shuffle([D, A, C, B]); // returns [A, B, D, C]

( code in playground )

关于reflection - Typescript - 代表任何类的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39976329/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com