Search code examples
javascripttypescriptclassecmascript-6generic-programming

Generic with interface class type


Could anyone explain why do I get the following error?

Property 'prop1' does not exist on type 'A'.ts(2339)

The code

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))
  }
}

Solution

  • You can do like this

    interface A {
      prop1: string
    }
    
    // constraint A1 with A
    class myClass <A1 extends A> {
      ptop1: string
      constructor(input: A1){
        this.ptop1 = input.prop1
      }
    }
    

    Playground