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?
It is just a way to pass types as arguments.
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 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.
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.
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
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