2016-08-22 1 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 красный и не действует.

Может ли кто-нибудь сказать мне, как сделать этот объект действительным для Typcript с минимальными изменениями? Мой проект довольно большой, и таких объектов много.

Спасибо за любую помощь

ответ

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

(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

Смежные вопросы