具有函数的Javascript对象不是打字稿有效的

时间:2016-08-22 12:42:08

标签: javascript typescript

我是TypeScript的新手,我有一个问题。我在Javascript中有项目,我在其中使用带有函数和语法的js对象是这样的:

var Player = {
  playing:1,
  stopped:2,
  paused:0,
  state: -1
}

Player.play = function(){
      this.state = this.playing;
      plugin.play();
}

Player.pause= function(){
      this.state = this.paused;
      plugin.pause();
}

Player.stop= function(){
      this.state = this.stoppe;
      plugin.stop();
}

但是当我想在Typescript中使用它时,everythink是红色的并且无效。

有人可以告诉我如何使这个对象对Typescript有效,尽可能少改变吗?我的项目很大,有很多像这样的对象。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

这是因为编译器不认为您的Player对象具有这些属性(playpausestop)。

interface IPlayer {
    playing: number;
    stopped: number;
    paused: number;
    state: number;

    play: () => void;
    pause: () => void;
    stop: () => void;
}

var Player = {
    playing: 1,
    stopped: 2,
    paused: 0,
    state: -1
} as IPlayer;

Player.play = function(){
      this.state = this.playing;
      plugin.play();
}

Player.pause = function(){
      this.state = this.paused;
      plugin.pause();
}

Player.stop = function(){
      this.state = this.stoppe;
      plugin.stop();
}

code in playground

或者你可以这样做:

var Player = {
    playing: 1,
    stopped: 2,
    paused: 0,
    state: -1,
    play: function() {
        this.state = this.playing;
        plugin.play();
    },
    pause: function() {
        this.state = this.paused;
        plugin.pause();
    },
    stop: function(){
        this.state = this.stoppe;
        plugin.stop();
    }
};

code in playground

相关问题