1

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?

1
  • That looks like a cast Commented Feb 4, 2016 at 22:13

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

omg, even such thing is covered in your book! Is it worth to read official TS handbook or shall I just skip to your book :)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.