Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning Promise from TypeScript Interface

interface IPlayer {
  id: String;
  name: String;
  dob: String;
  GetName<IPlayer>(): Promise<IPlayer>;
}

class Player implements IPlayer {
   constructor(public id: String, public name: string, public dob:string) { }

   GetName<IPlayer>(): Promise<IPlayer> {
     let player: IPlayer = new Player("Hello", "World", '');
   
     return new Promise<IPlayer>((resolve, reject) => { 
       resolve(player);
     });
   };
}

Not sure what I am doing wrong here. Can you please tell me why I am not able to create the instance of an interface in this code?

This is returning the error below:

Type 'Player' is not assignable to type 'IPlayer'.

let player: IPlayer ##

Can anyone help me with where I am doing this wrong in creating the instance of the interface?

like image 547
SkyArc Avatar asked Mar 29 '18 09:03

SkyArc


1 Answers

The problem is you declare IPlayer as a type parameter to GetName. This generic type parameter has no relation to the interface IPlayer. You can just remove the generic type parameter and it will work as expected:

interface IPlayer {
    id: String;
    name: String;
    dob: String;
    GetName(): Promise<IPlayer>;
}

class Player implements IPlayer {
    constructor(public id: String, public name: string, public dob: string) { }

    GetName(): Promise<IPlayer> {
        let player: IPlayer = new Player("Hello", "World", '');

        return new Promise<IPlayer>((resolve, reject) => {
            resolve(player);
        });
    };
}
like image 89
Titian Cernicova-Dragomir Avatar answered Oct 06 '22 08:10

Titian Cernicova-Dragomir