alphanumeric
alphanumeric

Reputation: 19329

Should be type placed on both sides of declaration

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:

  1. With MyType next to the variable name:
let myVar: MyType = { ID: "abc" };

  1. With MyType after the value:
let myVar = { ID: "abc" } as MyType;

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

Answers (2)

blurfus
blurfus

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

CertainPerformance
CertainPerformance

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

Related Questions