2016-08-22 76 views
0

我是TypeScript中的新成员,我有一个问题。我有项目在Javascript中,在那里我用JS与功能和语法对象是这样的:具有函数的Javascript对象不是打字稿有效

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

但是,当我想在打字稿everythink使用它是红色的,而不是有效的。

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

感谢所有帮助

回答

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

+0

中超,它的工作原理。谢谢 ! – Jouda