首页 > 解决方案 > 接口上不存在属性

问题描述

我对接口在 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 出现任何错误。

标签: angulartypescript

解决方案


那么这是否意味着当你在 TypeScript 中实现一个接口时,你只能使用接口中声明的属性和方法呢?

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

这是 OOP 中的一般概念。


推荐阅读