TypeScript/tests/cases/compiler/typeGuardConstructorPrimitiveTypes.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

41 lines
889 B
TypeScript

// @target: esnext
// Narrow a union of primitive types
let var1: string | number | boolean | any[] | symbol | bigint;
if (var1.constructor === String) {
var1; // string
}
if (var1.constructor === Number) {
var1; // number
}
if (var1.constructor === Boolean) {
var1; // boolean
}
if (var1.constructor === Array) {
var1; // any[]
}
if (var1.constructor === Symbol) {
var1; // symbol
}
if (var1.constructor === BigInt) {
var1; // bigint
}
// Narrow a union of primitive object types
let var2: String | Number | Boolean | Symbol | BigInt;
if (var2.constructor === String) {
var2; // String
}
if (var2.constructor === Number) {
var2; // Number
}
if (var2.constructor === Boolean) {
var2; // Boolean
}
if (var2.constructor === Symbol) {
var2; // Symbol
}
if (var2.constructor === BigInt) {
var2; // BigInt
}