谁能解释为什么我得到以下错误?
类型'A'不存在属性'prop1'.ts(2339)
代码
interface A {
prop1:string;
};
class myClass<A> {
ptop1: string;
constructor(input: A) {
this.ptop1 = input.prop1; //error happens in this line (Property 'prop1' does not exist on type 'A'.ts(2339))
}
}
答案 0 :(得分:1)
<A>
和类型interface A
之间存在冲突。此行myClass <A>
中的代码使myClass
类感到困惑,因此constructor (input: A)
语句在<A>
而不是interface A
中将A指向A。
您为什么不只使用这样的代码?
class myClass{
ptop1:string;
constructor(input:A){
this.ptop1=input.prop1;
}
}
答案 1 :(得分:1)
在您的班级中,<A>
表示通用;因此,在类内部,A
引用了泛型类型,而忽略了您可能先前已声明此符号的任何特定类型或接口。
通用类型表示任何类型,因此您只能使用通用参数,就好像它可以是任何和所有类型一样,因此您无法访问任何特定属性。
也就是说,在您的情况下,应使用更具体的T
类型,并使用implements
关键字来告诉编译器,通用类型T是实现A
接口的类型。 / p>
interface A {
p1: string
}
/* THIS DOES NOT WORK */
class c <T implements A> {
t1: string;
constructor(t: T){
this.t1 = t.p1
}
}
不幸的是,打字稿不允许使用通用声明中的T implements A
表达式;但是,可以通过滥用extends
关键字
interface A {
p1: string
}
class c <T extends A> {
t1: string;
constructor(t: T){
this.t1 = t.p1
}
}
答案 2 :(得分:0)
您可以这样做
interface A {
prop1: string
}
// constraint A1 with A
class myClass <A1 extends A> {
ptop1: string
constructor(input: A1){
this.ptop1 = input.prop1
}
}