Reputation: 19329
With the type MyType
being
export type MyType =
{
ID: string,
Name?: string
};
I can go ahead and declare variable myVar
using three slightly different syntax:
MyType
next to the variable name:let myVar: MyType = { ID: "abc" };
MyType
after the value:let myVar = { ID: "abc" } as MyType;
MyType
next to the variable name and after the value:let myVar: MyType = { ID: "abc" } as MyType;
Would be any difference in the resulting myVar
variable using any of three methods? What should be a preferred way and why?
Upvotes: 0
Views: 48
Reputation: 14031
In Option 1, you are declaring the variable as of a certain type and assigning it a value. If the value does not fit the type, it will complain at compile time. This is the preferred method as you get advanced warning that something might not match up correctly.
In Option 2, you are declaring a typeless variable and kind of casting the values to a certain type. This can be useful at times but also could give you run time errors, depending on usage (YMMV)
Option 3 is not really used as it's redundant, IMHO.
Upvotes: 0
Reputation: 370639
Using : someType
on the left hand side is type annotation. It indicates that the only thing assignable to the variable should be something of that type. When you need to indicate to TS that a variable should contain a particular type, that should be preferred.
You should avoid as
, which is type assertion - which basically tells the compiler "I'm sure I know what I'm doing, the expression on the left is really of type X even if you can't infer it." This should be avoided when possible, since it reduces the amount of type-checking TypeScript can do in some circumstances.
That said, often, you don't need either of those: that is, having TypeScript infer myVar
to be of type { id: string }
will probably work in most circumstances, especially if you aren't reassigning the variable (best to avoid variable reassignment when possible anyway - it's usually simple enough).
So, consider if you can do just
let myVar = { ID: "abc" };
without any typing at all. It'll be safe to use for, eg, arguments that expect something of MyType
, but without any type annotation or assertion (less unnecessary type noise often makes code more readable).
Upvotes: 1