TypeScript/tests/baselines/reference/intersectionNarrowing.types
Anders Hejlsberg a21f61f746
Fix narrowing of intersections of type variables and primitive types (#43131)
* Fix narrowing of intersections of type variables and primitive types

* Add tests
2021-03-18 08:55:50 -07:00

84 lines
1.9 KiB
Plaintext

=== tests/cases/conformance/types/intersection/intersectionNarrowing.ts ===
// Repros from #43130
function f1<T>(x: T & string | T & undefined) {
>f1 : <T>(x: (T & string) | (T & undefined)) => void
>x : (T & string) | (T & undefined)
if (x) {
>x : (T & string) | (T & undefined)
x; // Should narrow to T & string
>x : T & string
}
}
function f2<T>(x: T & string | T & undefined) {
>f2 : <T>(x: (T & string) | (T & undefined)) => void
>x : (T & string) | (T & undefined)
if (x !== undefined) {
>x !== undefined : boolean
>x : (T & string) | (T & undefined)
>undefined : undefined
x; // Should narrow to T & string
>x : T & string
}
else {
x; // Should narrow to T & undefined
>x : T & undefined
}
}
function f3<T>(x: T & string | T & number) {
>f3 : <T>(x: (T & string) | (T & number)) => void
>x : (T & string) | (T & number)
if (typeof x === "string") {
>typeof x === "string" : boolean
>typeof x : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function"
>x : (T & string) | (T & number)
>"string" : "string"
x; // Should narrow to T & string
>x : T & string
}
else {
x; // Should narrow to T & number
>x : T & number
}
}
function f4<T>(x: T & 1 | T & 2) {
>f4 : <T>(x: (T & 1) | (T & 2)) => void
>x : (T & 1) | (T & 2)
switch (x) {
>x : (T & 1) | (T & 2)
case 1: x; break; // T & 1
>1 : 1
>x : T & 1
case 2: x; break; // T & 2
>2 : 2
>x : T & 2
default: x; // Should narrow to never
>x : never
}
}
function f5<T extends string | number>(x: T & number) {
>f5 : <T extends string | number>(x: T & number) => void
>x : T & number
const t1 = x === "hello"; // Should be an error
>t1 : boolean
>x === "hello" : boolean
>x : T & number
>"hello" : "hello"
}