3 ms·
For types like those which are outside your control you can use type guards[1]: if (value == null) { // TS knows value is null, doesn't let you acc
by frankpf 8y ago
For types like those which are outside your control you can use type guards[1]:
if (value == null) {
// TS knows value is null, doesn't let you access value .length for example
} else if (Array.isArray(value)) {
// TS knows value is an array
} else {
// TS knows that it's an object here
}
However, having types like those in your own code (e.g. things like X[] | Y | null) is probably an antipattern and should be avoided. Using discriminated unions[2] is much better.
[1]: https://www.typescriptlang.org/docs/handbook/advanced-types.html https://www.typescriptlang.org/docs/handbook/advanced-types.... ("Type Guards and Differentiating Types" section)
[2]: [1]: https://www.typescriptlang.org/docs/handbook/advanced-types.html https://www.typescriptlang.org/docs/handbook/advanced-types.... ("Discriminated Unions" section)
- bmn__ 8y agoDeep links: https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-guards-and-differentiating-types https://www.typescriptlang.org/docs/handbook/advanced-types.... https://www.typescriptlang.org/docs/handbook/advanced-types.html#discriminated-unions https://www.typescriptlang.org/docs/handbook/advanced-types....