Closed
Description
Bug Report
π Search Terms
Narrowing Union literal
π Version & Regression Information
- This changed between versions 4.0.5 and 4.6.2
β― Playground Link
Playground link with relevant code
π» Code
// ------- EXPECTED -------
type Data1 = {
type: 'string',
a: string,
b: string
} | {
type: 'number',
a: number,
b: number
}
function test1(data: Data1) {
if (data.type === 'string') {
// Work as Expected: data.b is `string`
data.b
}
}
// ------- NOT EXPECTED -------
type Data2 = {
type: string,
a: string,
b: string
} | {
type: number,
a: number,
b: number
}
function test2(data: Data2) {
if (typeof data.type === 'string') {
// Expect: data.b is `string`
// Actual: data.b is `string | number
data.b
}
}
π Actual behavior
When discriminator property is not literal type in discriminated unions, type of Data2
is not narrowed as expected.
π Expected behavior
Type of Data2
can be narrowed just like Data1