Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does enclosing a class in angle brackets "<>" mean in TypeScript?

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?

like image 526
davejoem Avatar asked Aug 08 '16 14:08

davejoem


People also ask

What is the use of <> in TypeScript?

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.

What is angle bracket in JavaScript?

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 .

Are enclosed with angle brackets?

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>.

What is angular bracket?

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.


2 Answers

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

like image 120
Nitzan Tomer Avatar answered Sep 23 '22 20:09

Nitzan Tomer


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.

like image 40
James Monger Avatar answered Sep 22 '22 20:09

James Monger