【发布时间】:2021-03-31 13:37:09
【问题描述】:
我需要为特定类的Object.constructor 添加属性。
我正在使用lib.es5.d.ts
我尝试过覆盖全局对象,例如:
type EntityConstructor = Function & {behaviors: string[]}
declare global {
interface Object {
constructor: EntityConstructor
}
}
这会引发错误:
Subsequent property declarations must have the same type.
Property 'constructor' must be of type 'Function', but here has type 'EntityConstructor'.
我不需要这是一个覆盖它可能是一个显式类。
使用示例: 澄清我为什么以及如何想要这个属性...
我正在使用typescript mixins
我有一个方法,它采用一组 ConstrainedMixin 构造函数,将它们应用于基类,为混合类创建一个新的构造函数。然后我想将新构造函数上应用的 mixin 名称列表存储为新属性。这看起来像:
import compose from 'lodash.flowright';
export type ConstrainedMixin<T = {}> = new (...args: any[]) => T;
class Entity {
static behaves(...behaviors: Array<ConstrainedMixin>){
const newEnt = compose.apply(
null,
behaviors,
)(Entity);
newEnt.behaviors = behaviors.map((behaviorClass) => behaviorClass.name);
return newEnt;
}
}
【问题讨论】:
-
你能解释一下你会如何使用这样的东西吗?这与只为您的显式类提供一些
static属性有什么不同? -
@jcalz 添加了一个使用示例
-
为什么不能在
Entity中添加一个实例字段behaviors: string[]?如果您问的问题是“如何更改全局对象构造函数的类型?”,那么您可能正在做真的困难的方式。
标签: typescript types typescript-typings