Skip to content

narrowing object by property doesn't work if key isn't a const #51368

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
DetachHead opened this issue Nov 1, 2022 · 5 comments
Closed

narrowing object by property doesn't work if key isn't a const #51368

DetachHead opened this issue Nov 1, 2022 · 5 comments
Labels
Duplicate An existing issue was already created

Comments

@DetachHead
Copy link
Contributor

Bug Report

πŸ”Ž Search Terms

narrow property const

πŸ•— Version & Regression Information

4.9.0-dev.20221025

⏯ Playground Link

Playground link with relevant code

πŸ’» Code

interface Data {
    a?: number
}

declare const data: Data

let key = 'a' as const

if (data.a !== undefined) {
    key // "a"
    const a = data[key] // number | undefined
    const b = data['a'] // number
}

πŸ™ Actual behavior

data[key] is number | undefined

πŸ™‚ Expected behavior

data[key] is narrowed to number

@KotlinIsland
Copy link

KotlinIsland commented Nov 1, 2022

I managed to minify this issue a little bit, take a look below:

declare const data: {
    a?: number
}

if (data.a === undefined) throw "up"

const a = data['a' as 'a']
//    ^? const a: number | undefined
const b = data['a']
//    ^? const b: number

@fatcerberus
Copy link

Duplicate of #10530. Only certain patterns of property access induce narrowing, specifically only the forms obj.foo and obj['foo'] (i.e. the key must be a naked literal). obj[key] won't be narrowed, even if key is literal-typed.

@DetachHead
Copy link
Contributor Author

the example in that issue seems to have been fixed ages ago #10530 (comment)

@fatcerberus
Copy link

Yeah, foo["bar"] used to not be narrowable. Now it is, but the larger issue of foo[keyVar] not narrowing (which is a much bigger can of worms, implementation-wise) is still present.

@typescript-bot
Copy link
Collaborator

This issue has been marked as a 'Duplicate' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Duplicate An existing issue was already created
Projects
None yet
Development

Successfully merging a pull request may close this issue.

5 participants