【问题标题】:Typescript how to add properties to Object constructor?Typescript如何向对象构造函数添加属性?
【发布时间】: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


【解决方案1】:

你可以按照以下方式做一些事情:

type EntityConstructor = Function & {behaviors: string[]}

declare global {
  interface O extends Object {
    constructor: EntityConstructor
  }
}

但您需要创建另一个扩展Object 的类。据我所知,如果不更改原始Object 接口本身/ d.ts 文件或创建一个扩展Object 的单独类,就没有真正的方法可以满足您的要求。

以下是有关Overriding Interface Property Types 上相关问题的一些有用答案

【讨论】:

    猜你喜欢
    • 2019-04-20
    • 2021-04-26
    • 2019-11-24
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多