【问题标题】:Cannot use 'new' with the Function type in TypeScript不能在 TypeScript 中将“new”与 Function 类型一起使用
【发布时间】:2017-12-12 19:26:28
【问题描述】:

我有这个代码:

const BlockConstructors: Function[] = [
 OBlock,
 IBlock,
 TBlock
];

function randomFromArray(array: any[]) {
  return array[Math.floor( Math.random() * array.length )];
}

const BlockConstructor: Function = random(BlockConstructors);
const block: Block = new BlockConstructor();

我尝试从数组中绘制一些块构造函数,然后创建一个新对象,数组中的所有块构造函数都扩展了 Block 类。我得到错误:

不能将“new”与类型缺少调用或构造签名的表达式一起使用。

为什么会出现这个错误?

【问题讨论】:

  • Const 应该是一个 const 值,你不应该对一个 const 值进行新的引用。
  • 你为什么要创建一个无论如何都不会改变的东西的新实例? :)

标签: typescript


【解决方案1】:

您的代码不是独立的,但这是归结为原因。

Function 不是new-able。在 TypeScript 中只有三件事可以是 new'd:

  1. 带有 construct 签名的类型
  2. 没有构造签名但带有返回void调用签名的类型
  3. any

你真的想要第一个。

尝试从Function 切换到(new () => Block)

【讨论】:

    猜你喜欢
    • 2019-03-18
    • 2015-09-22
    • 2018-02-06
    • 1970-01-01
    • 2019-09-09
    • 2020-05-07
    • 2015-11-08
    • 2017-11-08
    • 2023-03-15
    相关资源
    最近更新 更多