TypeScript/tests/cases/compiler/typeGuardConstructorNarrowPrimitivesInUnion.ts
Austin Cummings ae3d28b5eb
Implement constructor type guard (#32774)
* Implement constructor type guard

* Fix code review issues for constructor type guard.
- Do not limit constructor expression to only identifiers
- Fix `assumeTrue` and operator no-narrow check
- Use better way to check that identifier type is a function
- Loosen restriction on what expr is left of ".constructor"
- Update typeGuardConstructorClassAndNumber test to include else cases

* Fix grammar & spacing in `narrowTypeByConstructor`

* fix bad merge

* switch (back?) to crlf

* update baselines

Co-authored-by: Nathan Shively-Sanders <293473+sandersn@users.noreply.github.com>
2020-03-11 13:16:33 -07:00

19 lines
397 B
TypeScript

// Union of primitives, number, arrays, and C1
let var1: number | "hello" | "world" | true | false | number[] | string[];
if (var1.constructor === Number) {
var1; // number
}
if (var1.constructor === String) {
var1; // "hello" | "world"
}
if (var1.constructor === Boolean) {
var1; // boolean
}
if (var1.constructor === Array) {
var1; // number[] | string[]
}