Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between angle brackets and "as'' in Typescript 2? [duplicate]

Tags:

typescript

What is the difference between using as or <> in the code below?

Option A - use 'as' for the return value

convertResultToParams(columnView:IColumnViewResult):IColumnViewParams {
    const params = {};

    Object.keys(this.getDefaultParams())
        .map(key => params[key] = columnView[key]);

    return params as IColumnViewParams;
}

Option B - use 'brackets' for the return value

convertResultToParams(columnView:IColumnViewResult):IColumnViewParams {
    const params = {};

    Object.keys(this.getDefaultParams())
        .map(key => params[key] = columnView[key]);

    return <IColumnViewParams>params;
}

And why can't I just declare the type in the variable declaration?

enter image description here

like image 312
user2954463 Avatar asked Sep 06 '17 16:09

user2954463


People also ask

What do angle brackets do in typescript?

It is just a way to pass types as arguments.

What is the difference between the angle brackets and the double quotes in a #include statement?

When you use angle brackets, the compiler searches for the file in the include path list. When you use double quotes, it first searches the current directory (i.e. the directory where the module being compiled is) and only then it'll search the include path list.

What do angle brackets mean in code?

What Does Angle Bracket Mean? The angle bracket (< or >), which is also called an “inequality sign” for its use in mathematics, is a kind of sideways caret that can be used to include tags or pieces of code. This ASCII set of characters is common in web design and other types of coding projects.

What do square brackets mean in typescript?

The square brackets means that we are talking about an object type. it has one property called 'type' of type string . The other part and is called a index signature.


1 Answers

Your interface probably has members that are required, so initializing to {} is not valid. You can cast {} to the interface type if you are initializing it then, and will add the fields shortly.

const params = {} as IColumnViewParams

Initially Typescript used <> for casting, but with the addition of jsx support this became a problem so the as casting operator was added. There is not difference in the casting, just the context where you can use them. as can be used anywhere, <> cannot be used in tsx

like image 200
Titian Cernicova-Dragomir Avatar answered Nov 30 '22 09:11

Titian Cernicova-Dragomir