Posts

Showing posts with the label Nullable

Can An Optional Parameter Be Null In TypeScript?

Answer : To answer my own question after trying... The types null and undefined are handled as separate types. The optional type is special, also allowing arguments to be left out of function calls. 1. Without a union or optional, nothing except the type itself is allowed. function foo(bar: string) { console.info(bar); } foo("Hello World!"); // OK foo(null); // Error foo(undefined); // Error foo() // Error 2. To additionally allow null , a union with null can be made. function foo(bar: string | null) { console.info(bar); } foo("Hello World!"); // OK foo(null); // OK foo(undefined); // Error foo() // Error 3. Allowing undefined works similarly. Note that the argument cannot be left out or null . function foo(bar: string | undefined) { console.info(bar); } foo("Hello World!"); // OK foo(null); // Error foo(undefined); // OK foo() // Error 4. You can also allow both, but the argument MUST still be given. function foo(b...