Finalmix6
Finalmix6

Reputation: 415

TypeScript : what does this variable declaration syntax mean?

Anyone know what does this mean :

myCollection: Collection|any = null;

?

I'm trying to figure it out but I am not sure..

Does it mean that myCollection is defined as a type of Collection, (which is an interface), and that its value is null by default? But if so, what does this :

|any

Means ?

Upvotes: 0

Views: 61

Answers (3)

jcalz
jcalz

Reputation: 328292

| is a union. The type A | B means "either A or B or both".

any is the any "type", which you generally shouldn't be using because it effectively turns off type checking by being assignable both to any other type and from any other type. This also means that any gobbles up any type that it appears with in a union or an intersection.

The type Collection | any therefore means "either a Collection or any type whatsoever". This reduces immediately to just any by the compiler, since that "either A or anything" is just "anything":

myCollection: Collection | any = null;
// (property) Foo.myCollection: any

So Collection | any is at best useful for documentation; as far as the compiler is concerned, Collection | goes away.

And the property is initialized to null.


I'm not sure if this is someone else's code or yours. If it's yours, consider changing to Collection | null if the intent is that the property can be a Collection or null. If it's someone else's, uh, ask them what's up with it I guess?

Playground link to code

Upvotes: 2

Pritam Kadam
Pritam Kadam

Reputation: 2527

In Collection|any this type, | indicates Union Type

Meaning of this is, variable mycollection can hold value of type Collection OR type of any.

Because mycollection can be of type any, null is valid value and typescript allows you to assign null to mycollection.

Upvotes: 1

Gregoire
Gregoire

Reputation: 24832

It means that myCollection can be of type Collection or of type any and it is initialized to null

Upvotes: 1

Related Questions