I am very new to TypeScript and I am loving it a lot, especially how easy it is to do OOP in Javascript. I am however stuck on trying to figure out the semantics when it comes to using angle brackets.
From their docs, I have seen several examples like
interface Counter { (start: number): string; interval: number; reset(): void; } function getCounter(): Counter { let counter = <Counter>function (start: number) { }; counter.interval = 123; counter.reset = function () { }; return counter; }
and
interface Square extends Shape, PenStroke { sideLength: number; } let square = <Square>{};
I am having trouble understanding what this exactly means or the way to think of/understand it.
Could someone please explain it to me?
They are using < > to pass the type parameters. So you decide to use the same. Don't let the < > intimidate you. It is just a way to pass types as arguments.
As you probably know, angle brackets in pairs are used: As a deprecated syntax for type-assertions. For manually specifying generic type parameters. For declaring elements in .
Angle brackets are commonly used to enclose a code of some type. For example, HTML tags and PageMaker tags are enclosed in angle brackets. They are also used on chat channels and in chat rooms to frame a comment or expression, such as <groan!> or <g>, which is short for <grin>.
Angle brackets, sometimes known as chevrons, are a pair of punctuation marks that take the form of < and >. These marks are often considered to be a type of bracket, the same category that parentheses, square brackets, and curly brackets/braces are considered to belong to.
That's called Type Assertion or casting.
These are the same:
let square = <Square>{}; let square = {} as Square;
Example:
interface Props { x: number; y: number; name: string; } let a = {}; a.x = 3; // error: Property 'x' does not exist on type `{}`
So you can do:
let a = {} as Props; a.x = 3;
Or:
let a = <Props> {};
Which will do the same
This is called Type Assertion.
You can read about it in Basarat's "TypeScript Deep Dive", or in the official TypeScript handbook.
You can also watch this YouTube video for a nice introduction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With