2016-08-22 37 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

相關問題