gpt4 book ai didi

typescript - 从装饰器访问泛型类的静态成员

转载 作者:搜寻专家 更新时间:2023-10-30 21:12:21 26 4
gpt4 key购买 nike

我有一个装饰类:

@Decorator
class Entity {
public static member: string[] = [];
}

使用装饰器:

function Decorator<T extends { new(...args: any[]): Entity }>(constructor: T) {
return class extends constructor {
constructor(...args: any[]) {
super(...args);
// Do some things
constructor.prototype.member.map((v: string) => {
// Do things with the elements of the static array.
});
}
};
}

虽然这可行,但通过使用 any 类型的 constructor.prototype 我失去了原型(prototype)中已有的 member 的类型检查作为字符串数组。

有没有不丢失类型检查的解决方案?

编辑:我也测试过:

function Decorator<T extends { prototype: typeof Entity; new(...args: any[]): Entity; }>(constructor: T) {
return class extends constructor {
constructor(...args: any[]) {
super(...args);
// Do some things
constructor.prototype.member.map((v) => {
// Do things with the elements of the static array.
});
}
};
}

但这会在 @Decorator 行中产生错误:

Property 'prototype' is missing in type 'Entity'.'

Edit2:我也测试过:

function Decorator<T extends typeof Entity>(constructor: T) {
// This works and returns an Entity.
const x = new constructor({} as any);
// This doesn't work. Tsc says: 'Type 'T' is not a constructor function type.'
return class extends constructor {
constructor(...args: any[]) {
super(...args);
// This now works:
constructor.member.map((v) => {
// ...
});
}
};
}

但这会在 @Decorator 行中产生错误:

Property 'prototype' is missing in type 'Entity'.'

最佳答案

你可以这样做:

(constructor.prototype as typeof Entity).member...

然后你就会有类型安全,例如:

(constructor.prototype as typeof Entity).member2..

将导致:

Property 'member2' does not exist on type 'typeof Entity'.


编辑

你不能那样做。
静态成员/函数不是原型(prototype)的一部分,要实现您想做的,它应该如下所示:

function Decorator<T extends { prototype: Entity; new(...args: any[]): Entity; }>(constructor: T) { ... }

(不同之处在于 prototype: Entity 而不是 typeof Entity),那么您收到的错误将消失。
但是,你会得到这样的错误:

Property 'member' does not exist on type 'Entity'

因为它是静态成员。

Entity类的编译js中很容易看出:

var Entity = (function () {
function Entity() {
}
return Entity;
}());
Entity.member = [];

很明显,member 不是原型(prototype)的一部分。

正如我原来的回答所说,这就是您需要强制转换它的原因。


第二次编辑

这里有一些有用的东西,可能就是您想要的:

type EntityStatic = {
new (...args: any[]): Entity;
member: string[];
}

function Decorator(constructor: EntityStatic) {
...
}

关于typescript - 从装饰器访问泛型类的静态成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45347630/

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