'Why is TypeScript unable to infer the type properly?
I have two examples where TypeScript type inference is not working as I expect it, maybe these two are related, maybe it's a TS bug, maybe I am only too dumb to understand it.
Example #1
interface AType {
type: 'A'
message: string
}
interface BCType {
type: 'B' | 'C'
}
type Test = AType | BCType
function doSomething(test: Test) {
if (test.type !== 'B' && test.type !== 'C') {
test.message
}
}
The test.message gets the error
Property 'message' does not exist on type 'Test'.
Property 'message' does not exist on type 'BCType'.ts(2339)
Why isn't test of AType now, so it has a message property? If I remove the 'C' from the type, it works. If I check for === 'A', is also works.
Example #2
interface AType {
type: {
id: 'A'
}
message: string
}
interface BType {
type: {
id: 'B'
}
}
type Test = AType | BType
function doSomething(test: Test) {
if (test.type.id === 'A') {
test.message
}
}
Same here:
Property 'message' does not exist on type 'Test'.
Property 'message' does not exist on type 'BType'.ts(2339)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
