从TypeScript接口返回Promise

时间:2018-03-29 09:17:42

标签: typescript interface es6-promise

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

请注意确定我做错了。你能否告诉我为什么我无法在这段代码中创建接口实例?

这将返回以下错误。

类型'播放器'不能分配给'IPlayer'类型。

让玩家:IPlayer

在创建界面实例时,任何人都可以帮助我解决这个问题吗?

1 个答案:

答案 0 :(得分:5)

问题是您将IPlayer声明为GetName的类型参数。此泛型类型参数与接口IPlayer无关。您可以删除泛型类型参数,它将按预期工作:

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