【问题标题】:Property does not exist on interface接口上不存在属性
【发布时间】:2019-07-22 00:51:33
【问题描述】:

我对接口在 TypeScript 中的工作方式感到困惑。

这是一段代码:

interface test1 {
}

class test2 implements test1
{
    public foo;
}

let test: test1 = new test2();

test.foo = 'test';

不会编译报错“property foo does not exist on type test1。那是不是意味着你在TypeScript中实现接口时,只能使用接口中声明的属性和方法?

我很困惑,因为我习惯了 PHP,这不会导致 PHP 出现任何错误。

【问题讨论】:

  • 正如 zmag 所说,这就是 OOP 中的一般思想。 (您可以阅读有关协变和逆变的内容,这很有趣;))

标签: angular typescript


【解决方案1】:

那是不是意味着你在 TypeScript 中实现接口时,只能使用接口中声明的属性和方法?

没有。这意味着当你在 TypeScript 中引用具有特定接口的变量时,你只能使用在该变量的接口中声明的属性和方法。

这是 OOP 中的一般概念。

【讨论】:

  • 好的,我明白了,想了很多,这是有道理的,但我很困惑,因为它不会导致 PHP 出错,所以我想知道是 PHP 的行为异常还是TypeScript,我现在有答案了。
【解决方案2】:
let test: test1 = new test2();

test.foo = 'test';

您将test1 分配为test 变量的类型,test1 接口中没有foo 属性。所以这就是你收到这个错误的原因。如果将类型更改为let test: test2: new test2();。它不会抛出任何错误:

let test: test2 = new test2();

test.foo = 'test';

【讨论】:

  • 确实可以编译,但我想使用一个接口,这样我就可以让多个类通过相同的类型检查作为函数的参数。这是我的具体实现: let block: BlockInterface = new QuestionBlock();函数 someFunction(block: BlockInterface) { ....}
【解决方案3】:

在这里考虑两件事

  1. 如果要初始化一个变量,不需要提供类型。
interface test1 { }
class test2 implements test1{
    public foo;
}
let test = new test2();
test.foo = 'test';
  1. 如果您仍想在初始化值之前设置类型,您可以使用 Options。

选项 1

interface test1 { }
class test2 implements test1{
    public foo;
}
let test: test2 = new test2();
test.foo = 'test';

选项 2

interface test1 { }
class test2 implements test1{
    public foo;
}
let test: test1 | any = new test2();
test.foo = 'test';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2019-10-12
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多