接口上不存在属性

问题描述 投票:0回答:3

我对TypeScript中的接口如何工作感到困惑。

这是一大堆代码:

interface test1 {
}

class test2 implements test1
{
    public foo;
}

let test: test1 = new test2();

test.foo = 'test';

它不会编译并给出错误“类型test1上不存在属性foo。这是否意味着当您在TypeScript中实现接口时,您只能使用接口中声明的属性和方法?

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

angular typescript
3个回答
2
投票

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

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

这是OOP中的一般概念。


1
投票
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';

0
投票

想想这里有两件事

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

选项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';
© www.soinside.com 2019 - 2024. All rights reserved.