# Narrowing
typeof, instanceof
are type guards.
# typeof
- Note:
typeof null
= objecttypeof []
= object
function foo(x: number | string): string {
if (typeof x === 'number') {
return x + 1; // number
}
return 'hello' x; // string
}
function foo(x: string | string[] | null): string {
if (typeof x === 'object' && x) {
// string[]
}
if (typeof x === 'object') {
// string[] | null
}
if (typeof x === 'string') {
// string
}
return x + '';
}
// == null - checks for both null, undefined
let foo = undefined;
if (foo == null) {
console.log(foo); // undefined
}
# instanceof
function foo(x: string | Date) {
if (x instanceof Date) {
// Date
}
// string
}
# Assignment
let foo: number | string;
foo = 32;
foo = 'hi';
foo = true; // error