打字稿如何向对象构造函数添加属性?
Typescript how to add properties to Object constructor?
我需要在特定 class 上向 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'.
我不需要将其作为显式 class.
的覆盖
用法示例:
阐明我为什么以及如何想要这个 属性...
我正在使用typescript mixins
我有一个方法,它采用一组 ConstrainedMixin
构造函数,将它们应用于基础 class,为混合 class 创建一个新的构造函数。然后我想将应用的 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;
}
}
您可以按照以下方式做一些事情:
type EntityConstructor = Function & {behaviors: string[]}
declare global {
interface O extends Object {
constructor: EntityConstructor
}
}
但是您需要创建另一个扩展 Object
的 class。据我所知,如果不更改原始 Object
界面本身/ d.ts 文件或创建一个单独的 class 扩展 Object
.
以下是
上相关问题的一些有用答案
我需要在特定 class 上向 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'.
我不需要将其作为显式 class.
的覆盖用法示例: 阐明我为什么以及如何想要这个 属性...
我正在使用typescript mixins
我有一个方法,它采用一组 ConstrainedMixin
构造函数,将它们应用于基础 class,为混合 class 创建一个新的构造函数。然后我想将应用的 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;
}
}
您可以按照以下方式做一些事情:
type EntityConstructor = Function & {behaviors: string[]}
declare global {
interface O extends Object {
constructor: EntityConstructor
}
}
但是您需要创建另一个扩展 Object
的 class。据我所知,如果不更改原始 Object
界面本身/ d.ts 文件或创建一个单独的 class 扩展 Object
.
以下是