【问题标题】:Property 'x' is missing in Type 'y'类型“y”中缺少属性“x”
【发布时间】:2016-11-22 03:51:07
【问题描述】:

此代码在 TypeScript 1.8 之前编译,现在不再编译。

//[in app3.ts]
declare module App {

    export interface Iaa {
        nb: number;
    }

    export interface Ibb extends Iaa {
        title: string;
    }

}

//[in app4.ts:]
/// <reference path="app3.ts"/>

module App {
"use strict";

export interface Iaa extends aa {
}

export class aa {

    constructor() {
    }

    test(): void {
        var that: Iaa = <Iaa>this; //Error
    }
}

export interface Ibb extends bb{
}

export class bb extends aa {

    constructor() {
        super();
    }

    test(): void {
        var that: Ibb = <Ibb>this;//Error
        that.nb = 10;
    }

}
}

这是错误: app4.ts(15,29):错误 TS2352:类型“this”和类型“Iaa”都不能分配给另一个。 类型“aa”不可分配给类型“Iaa”。 类型“aa”中缺少属性“nb”。

谁能解释一下为什么“nb”和“title”在 app3.ts 中时未定义? 谢谢

【问题讨论】:

  • 为什么接口扩展类?
  • 来自官方文档:“当接口类型扩展类类型时,它继承类的成员而不是它们的实现”
  • 所以错误几乎可以解释自己 - aa 中没有属性 nb
  • 我的问题是为什么这段代码在 1.8 之前编译。
  • 看起来是个错误

标签: typescript interface


【解决方案1】:

回答你的问题:

谁能解释一下为什么“nb”和“title”在 app3.ts 中时未定义?

这可能是因为您尝试放入Iaa 的一个aa 实例,它与Iaa 没有共同之处(没有属性匹配)。要能够做到这一点aa 需要实现Iaa 或至少具有相同的属性。 Ibb的情况相同

这里有如何让你的代码再次工作。

declare module App {

    export interface Iaa {
        nb: number;
    }

    export interface Ibb extends Iaa {
        title: string;
    }

}

module App {
    "use strict";

    export interface Iaa extends aa {
    }

    export class aa {

        constructor() {
        }

        test(): void {
            var that: Iaa = <Iaa>this; //Error
        }

        nb: number; // <-- add that
    }

    export interface Ibb extends bb {
    }

    export class bb extends aa {

        constructor() {
            super();
        }

        test(): void {
            var that: Ibb = this as Ibb;//Error
            that.nb = 10;
        }

        title: string; // <-- add that
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-03
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 2015-12-02
    • 2019-02-07
    相关资源
    最近更新 更多