我是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有效,尽可能少改变吗?我的项目很大,有很多像这样的对象。
感谢您的帮助
答案 0 :(得分:0)
这是因为编译器不认为您的Player
对象具有这些属性(play
,pause
和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();
}
或者你可以这样做:
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();
}
};