具有接口类类型的泛型

时间:2020-10-10 11:00:42

标签: javascript typescript class ecmascript-6 generic-programming

谁能解释为什么我得到以下错误?

类型'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))
  }
}

3 个答案:

答案 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
  }
}

Playground