简体   繁体   中英

Javascript object with functions is not typescript valid

I am new in TypeScript and I have one question. I have project in Javascript, where I use js object with functions and syntax is like this:

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

But when I want to use it in Typescript everythink is red and not valid.

Can someone tell me how to to make this object valid for Typescript with as little change as possible? My project is quite big and there is lot of objects like this.

Thanks for any help

That's because the compiler doesn't think that your Player object has these properties ( play , pause and stop ).

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 )

Or you can just do this:

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM