打字稿:类返回空对象

时间:2019-02-14 16:04:06

标签: typescript

我得到这个Typescript类的目的是想让它工作,但由于某种原因,它在我实例化后不会给我正确的类实例

Class GamesService

export interface IGame {
  name: string;
  online: number;
  likes: number;
  playedCount: number;
  images: {
    small: string;
    medium: string;
    large: string;
  }
}

export class GamesService {
  public getGames(): IGame[] {
    return []
  }
}

用法

private getGames(): IGame[] {
 const GS = new GamesService();

 console.log(GS);

 return [];
}

console.log返回以下结果:GamesService {}我期望GamesService {getGames: f()}

有人可以帮我吗,对打字稿来说还很新:)

2 个答案:

答案 0 :(得分:1)

该对象正确并且可以工作。您所看到的只是console.log()的输出行为。您可以尝试调用GS的方法进行确认。

答案 1 :(得分:1)

Typescript将您的代码转换为javascript这样的代码-

var GamesService = (function () {
    function GamesService() {
    }
    GamesService.prototype.getGames = function () {
        return [];
    };
    return GamesService;
}());
var GS = new GamesService();
console.log(GS);

它输出像这样- enter image description here