Reputation: 26467
When reading TypeScript handbook, I came across following example:
interface Shape {
color: string;
}
interface Square extends Shape {
sideLength: number;
}
var square = <Square>{};
square.color = "blue";
square.sideLength = 10;
The question is - what is actually <Square>{}
? Seems like a bizarre syntax to me. From Java/C# point of view, it's like a generic of an anonymous object. What exactly is it and what are the limitations of such creation?
Upvotes: 1
Views: 194
Reputation: 276115
Its called a Type Assertion https://basarat.gitbooks.io/typescript/content/docs/types/type-assertion.html
And the pattern you are looking at:
var square = <Square>{};
square.color = "blue";
square.sideLength = 10;
Is common (but not recommended) for JS -> TS Migration for lazy object initialization : https://basarat.gitbooks.io/typescript/content/docs/tips/lazyObjectLiteralInitialization.html
Upvotes: 3
Reputation: 8843
It's "casting". Interpret the following thing ({}
, an object literal with no fields) as a Square
basically. So because of the usage of that the square
will be inferred to be of type Square
by the TypeScript compiler and Intellisense will show the correct members.
Of course it's not real "casting", as we know types are just an illusion in TypeScript. It's all for the compiler.
Upvotes: 4