shal
shal

Reputation: 3024

TypeScript: Define type that can be bool or null

I have a function that can return either true, false or null.

How do I define this type? For now, as a temporary solution, I define it as boolean | string, but it's misleading, someone may thing that it really may return string... Any ideas?

Upvotes: 24

Views: 38362

Answers (3)

Vasilis Plavos
Vasilis Plavos

Reputation: 583

It works like this:

let isItNullable: boolean | null = true;
isItNullable = null;
console.log(isItNullable);

Upvotes: 2

RafaelJan
RafaelJan

Reputation: 3608

By default, null and undefined are subtypes of all other types, so you just specify that the return value is boolean and you are good.

function foo(): boolean {

    return null; // OK
}

Upvotes: 0

Bruno Grieder
Bruno Grieder

Reputation: 29824

It depends on which typescript version you are using.

  • before 2.0 null can be returned on ("is in the domain of") any type, so boolean is your type

  • starting with 2.0, if you enable --strictNullChecks then you have to specify that a type can return null. So your type will be boolean | null

More details here paragraph Non-nullable Types

Upvotes: 33

Related Questions