我对TypeScript中的接口如何工作感到困惑。
这是一大堆代码:
interface test1 {
}
class test2 implements test1
{
public foo;
}
let test: test1 = new test2();
test.foo = 'test';
它不会编译并给出错误“类型test1上不存在属性foo。这是否意味着当您在TypeScript中实现接口时,您只能使用接口中声明的属性和方法?
我很困惑,因为我已经习惯了PHP,这不会导致PHP出现任何错误。
那么这是否意味着当您在TypeScript中实现接口时,您只能使用接口中声明的属性和方法?
不。这意味着当您在TypeScript中引用具有特定接口的变量时,您只能使用在变量接口中声明的属性和方法。
这是OOP中的一般概念。
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';
想想这里有两件事
interface test1 { } class test2 implements test1{ public foo; } let test = new test2(); test.foo = 'test';
选项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';