- What is difference between let and var while declaring variable?
var is Function Scoped and let is block scoped
Using varvar foo = 123; if (true) { var foo = 456; } console.log(foo); // 456
Using let
let foo = 123; if (true) { let foo = 456; } console.log(foo); // 123
- What would be the value of the below variables?
//Value is Undefined var foo:string; //You can explicitly define value as undefined var age = undefined; //any is a valid value which is default type until the variable assumes some data type by type inference var location:any; //undefined and null could be assigned to any of the datatype var pincode:any=undefined; var state:any=null;
- Why the below is not possible in interface?
I am having a interface and class like one below which results in compile time exceptioninterface test1 { } class test2 implements test1 { public foo; } let test: test1 = new test2(); test.foo = 'test';
The reason for the compilation error is when you reference a variable with specific interface in TypeScript, you can only use the properties and methods declared in the interface of the variable
You are assigning test1 as a type of test variable, test1 interface doesn’t have foo property in it. so that’s why you are getting this error. If you change the type to let test: test2: new test2();. it won’t throw any error like one belowlet test: test2 = new test2(); test.foo = 'test';
There are two workaround for this. One is not to define the type while initializing variable like one below
interface test1 { } class test2 implements test1{ public foo; } let test = new test2(); test.foo = 'test';
Other is to use any while initializing variable
interface test1 { } class test2 implements test1{ public foo; } let test: test1 | any = new test2(); test.foo = 'test';