Skip to content
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

in operator does not narrow string type to index object #48972

Closed
deser opened this issue May 5, 2022 · 4 comments
Closed

in operator does not narrow string type to index object #48972

deser opened this issue May 5, 2022 · 4 comments
Labels
Duplicate An existing issue was already created

Comments

@deser
Copy link

deser commented May 5, 2022

Example:

const meow: string = 'domain1'

const hosts = {
    "domain1": {color: 'red'},
    "domain2": {color: 'blue'},
}

if(meow in hosts) {
   hosts[meow]
}

Playground:
https://www.typescriptlang.org/play?#code/MYewdgzgLgBAtgUxAdwFw2gJwJZgOYwC8MA5ACYhwCGuAjCQFAOiSwAWI0ERMA3gzEEwARBWp1h6XqAA2ITOhKYEZEgF8ANAKGjKNMACZJfWfMUAjGQFcE6rWqbYAZgApEKGLhgcuASj7a3pxQEADa7sgAugwOQA

Expected behavior:
meow can be used to index hosts if verification with in operator is done.

@torcoste
Copy link

torcoste commented May 5, 2022

This will work as you would expect if you do not forcibly set the type for meow

const meow = 'domain1'

const hosts = {
    "domain1": {color: 'red'},
    "domain2": {color: 'blue'},
};

if(meow in hosts) {
   hosts[meow]
}

Playground

@jcalz
Copy link
Contributor

jcalz commented May 5, 2022

You forgot fill out the issue template completely.

This is working as intended. Non-union types are not narrowed upon assignment. Duplicate of or strongly related to #16976 Edit: I missed the point here, the ask is not that meow be narrowed to "domain1", but that it presumably should be narrowed to keyof typeof hosts.

This is a duplicate of #43284

@fatcerberus
Copy link

Assuming this worked (allowing arbitrary strings as indexers after an in check), objects can legally have extra properties thanks to structural subtyping—so what is the type of hosts[meow] then?

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label May 5, 2022
@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

No branches or pull requests

6 participants