打字稿:如果我将变量类型定义为接口类型,则会出现错误

时间:2016-08-05 05:29:45

标签: typescript

在下面的代码中,当我尝试将变量定义为接口类型时,我在语句(emp:IEmployee= { FirstName: "Saurabh", LastName: "Vats" };)中收到错误。为什么TypeScript在这里给我错误?

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;
    constructor(element: HTMLElement) {
        this.element = element;
        this.element.innerHTML += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerHTML = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

    print(employee: IEmployee) {
        console.log(employee.FirstName + employee.LastName);

    }

}

interface IEmployee {
    FirstName: string;
    LastName: string;
}
window.onload = () => {
    var el = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
    emp:IEmployee= { FirstName: "Saurabh", LastName: "Vats" };
    greeter.print(emp);

};

1 个答案:

答案 0 :(得分:2)

您只是错过了一个关键字。

这是不正确的:

emp:IEmployee= { FirstName: "Saurabh", LastName: "Vats" };

应该是:

let emp:IEmployee= { FirstName: "Saurabh", LastName: "Vats" };

<小时/> 但是,如果由于某种原因,你想让它成为一个全局变量呢?

在javascript中,如果你写过:

emp = { FirstName: "Saurabh", LastName: "Vats" };

您实际上会将其添加到window对象。

你仍然可以在打字稿中做到这一点,你只需要明确它:

interface Window {
    emp:IEmployee;
}

window.onload = () => {
     var el = document.getElementById('content');
     var greeter = new Greeter(el);
     greeter.start();
     window.emp = { FirstName: "Saurabh", LastName: "Vats" };
     greeter.print(emp);
};