'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?



Solution 1:[1]

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

Solution 2:[2]

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
}

Solution 3:[3]

It works like this:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bruno Grieder
Solution 2
Solution 3 Vasilis Plavos