【问题标题】:Default constructable class types in TypescriptTypescript 中的默认可构造类类型
【发布时间】:2017-07-03 00:57:34
【问题描述】:

我正在尝试使用带有此签名的 TypedJSON 函数:

parse<T>(text: string, type: {
    new (): T;
}, settings?: SerializerSettings): T;

我想要的功能与此类似:

function processJson<T>(json: string, processor: (jsonObject: T) => any): void {
    let t: T;
    let ob = TypedJSON.parse(json, t);
    processor(ob);
}

但是这不会进行类型检查,因为:

“T”类型的参数不能分配给“new () => {}”类型的参数。

所以我添加了一些额外的类型信息:

function processJson<T extends { new (): T; }>(json: string, processor: (jsonObject: T) => any): void {
    let t: T;
    let ob = TypedJSON.parse(json, t);
    processor(ob);
}

现在该类型检查但当我开始使用它时......

@JsonObject
class Foo {
    @JsonMember
    public X: number;
}

processJson<Foo>("{'X': 12}", (f: Foo) => {});

...我收到此错误:

类型“Foo”不满足约束“new () => Foo”。类型“Foo”不匹配签名“new (): Foo”。

当然我可以做到这一点没问题:

let f = new Foo();

我是 Typescript 的新手。有什么魔法咒语可以解决这个问题吗?或者如果失败了,有什么方法可以忽略这种类型检查吗?

【问题讨论】:

  • 你可以在定义类的同时定义interface Foo { new (): Foo; }
  • 是的,我尝试添加interface&lt;T&gt; DefaultConstructable { new (): T },然后添加class Foo implements DefaultConstructable&lt;Foo&gt; { ...。它可以工作,但是告诉编译器一些它应该已经知道是真的东西是很多样板。
  • 不,我的意思是在class Foo 定义之后添加interface Foo { new (): Foo; },就是这样。 (class Foo implements...不需要)
  • 嗯,这行得通,但如果我必须为每节课都这样做,那实际上仍然是很多样板。
  • 顺便说一句,泛型类型信息在运行时不可用,所以我认为你不能在这里使用泛型(检查ob instanceof Foo)。

标签: typescript


【解决方案1】:

这似乎通过放弃打字来解决问题:

let ob = TypedJSON.parse(json, t as any);

Related question.

【讨论】:

    猜你喜欢
    • 2012-04-14
    • 1970-01-01
    • 2021-06-06
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多