Description
TypeScript Version: 3.4.4 and typescript@3.6.0-dev.20190623
Search Terms:
Code
type someType = {
name: 'first',
first: string,
} | {
name: 'second',
second: string,
}
function someFunction(arg1: someType, arg2: someType) {
if (arg1.name === arg2.name) {
if (arg1.name === 'first') {
// Here compiler shows an error
console.log(arg2.first)
}
}
}
Expected behavior:
Since arg1 and arg2 have same names property first should also exist on arg2
Actual behavior:
Property 'first' does not exist on type 'someType'.
Property 'first' does not exist on type '{ name: "second"; second: string; }'.ts(2339)
Playground Link:
https://www.typescriptlang.org/play/#src=type%20someType%20%3D%20%7B%0D%0A%20%20name%3A%20'first'%2C%0D%0A%20%20first%3A%20string%2C%0D%0A%7D%20%7C%20%7B%0D%0A%20%20name%3A%20'second'%2C%0D%0A%20%20second%3A%20string%2C%0D%0A%7D%0D%0A%0D%0Afunction%20someFunction(arg1%3A%20someType%2C%20arg2%3A%20someType)%20%7B%0D%0A%20%20if%20(arg1.name%20%3D%3D%3D%20arg2.name)%20%7B%0D%0A%20%20%20%20if%20(arg1.name%20%3D%3D%3D%20'first')%20%7B%0D%0A%20%20%20%20%20%20%2F%2F%20Here%20compiler%20shows%20an%20error%0D%0A%20%20%20%20%20%20console.log(arg2.first)%0D%0A%20%20%20%20%7D%0D%0A%20%20%7D%0D%0A%7D
Activity
jcalz commentedon Jun 24, 2019
Duplicate of #12184, I think.
fatcerberus commentedon Jun 24, 2019
This can only narrow
arg1
. TS only narrows variables directly involved in the conditional expression and doesn't track relationships with other variables.typescript-bot commentedon Jun 26, 2019
This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.