gpt4 book ai didi

typescript - 无法在 Typescript 中定义类类型

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

我正在尝试在 Typescript 中定义“定义”类型。定义可以是类构造函数或对象 - 稍后我会这样做:

 if (this._isConstructor(definition)) {
return new definition(...args); // is a class - instantiate it
}

return definition; // is just an object - return it

我的类型定义为:

type Definition = {
new (arg?: object): object | object
}

这似乎有效。然而,它看起来很难看,我想把它分成:

type Definition = {
Cstruct | object
}

type Cstruct = new (arg?: object): object

然而那是呻吟

Cannot use 'new' with an expression whose type lacks a call or construct signature

尝试“新建”它时。

最佳答案

使用 type guard 的解决方案:

type Definition = Cstruct | object
type Cstruct = {new (arg?: object): object}

function isConstructor(def: Definition): def is Cstruct {
// Here implement your test and return true or false
return true
}

function getObject(def: Definition, args = []) {
if (isConstructor(def))
return new definition(...args);
return def;
}

关于typescript - 无法在 Typescript 中定义类类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46542655/

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