0

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 ?

3 Answers 3

2

| 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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.