saurabh vats saurabh vats - 4 months ago 18
TypeScript Question

Typescript: If am defining a variable type as interface type am getting error

In the below code I am getting an error in statement (

emp:IEmployee= { FirstName: "Saurabh", LastName: "Vats" };
) when am trying to define a variable as interface type. Why is TypeScript is giving me error here?

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

};

Answer

You're just missing a keyword.

This is incorrect:

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

It should be:

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


But what if, for some reason, you wanted to make it a global variable?

In javascript, if you had written:

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

You would actually be adding this to the window object.

You can still do this in typescript, you just have to be explicit about it:

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