I am new on typescript and wondering what is different between : <type> vs xxx as <type>? and how should I know where to use which one?
let abc: any = {}
let abc = {} as any
I am new on typescript and wondering what is different between : <type> vs xxx as <type>? and how should I know where to use which one?
let abc: any = {}
let abc = {} as any
On
What it means
The syntax variable: type is called a type annotation. It states that the variable will contain values of the specified type throughout its lifetime, and asks the typescript compiler to verify that this is the case.
The syntax expression as type is called a type assertion. It says that you know the expression will yield a value of this type, and asks the compiler to believe you.
Why both exist
Type annotations are needed because it is possible to declare a variable without assigning a value to it, and also because it is possible to assign a new value later, so the value initially assigned may not be representative of all the values the variable will hold throughout its lifetime.
Type assertions are needed in case the programmer actually knows more about the type than the compiler.
Which to use?
Generally speaking, you should favor type annotations so the compiler checks you are correct, and catches more bugs. For instance, consider:
let person: Person = {}; // error: property name is missing
vs
let person = {} as Person; // the compiler believes you
person.name.toUpperCase(); // runtime error because name is undefined
However, sometimes you might really know more the compiler does, in which case only a type assertion will get the point across (though there are nearly always better ways).
Appendix: Avoid any
While we're on the subject of best practices, you should avoid any whenever possible, because it bypasses type checks, too:
let obj: any = {}; // totally correct
let person: Person = obj; // compiler believes you, because any is special
person.name.toUpperCase(); // runtime error, because name is undefined
The first one is called type annotation and the second one is called type assertion and there isn't any difference between those concepts in this case.