Skip to content

as const does not narrow when object literal defined with type #45287

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
jisaacks opened this issue Aug 2, 2021 · 3 comments
Closed

as const does not narrow when object literal defined with type #45287

jisaacks opened this issue Aug 2, 2021 · 3 comments
Labels
Duplicate An existing issue was already created

Comments

@jisaacks
Copy link

jisaacks commented Aug 2, 2021

Bug Report

🔎 Search Terms

Searched:

typeof doesn't narrow, ignores as const when object literal defined with type

🕗 Version & Regression Information

Example in playground

💻 Code

interface A {
    [k: string]: 'foo' | 'bar' | 'baz' | 'other'
}

const foo:A = {
    a: 'foo',
    b: 'bar',
} as const

type FooKeys = keyof typeof foo

🙁 Actual behavior

Since foo is defined as A the typeof ignores the as const and FooKeys ends up being string | number

🙂 Expected behavior

I would expect foo being defined with as const would narrow to a type with only a and b keys.
So I would expect FooKeys to be "a" | "b"


Workaround

interface A {
    [k: string]: 'foo' | 'bar' | 'baz' | 'other'
}

const bar = {
    a: 'foo',
    b: 'bar',
} as const

const foo:A = bar

type FooKeys = keyof typeof bar

If this is not a bug

If this is actually expected, can this issue be transferred into a feature request?

@RyanCavanaugh
Copy link
Member

See #7481

@RyanCavanaugh RyanCavanaugh added the Duplicate An existing issue was already created label Aug 2, 2021
@jcalz
Copy link
Contributor

jcalz commented Aug 2, 2021

This is working as intended and doesn't have much to do with as const.

A is not a union type, so the assignment of a value of type { readonly a: "foo"; readonly b: "bar"; } to a variable annotated as type A does not result in any narrowing via control flow analysis. The variable foo is of type A; it is not narrowed by assignment; its keys are keyof A.

If you're asking that control flow analysis take place on non-union types, then this might be a duplicate of #16976.

@jisaacks
Copy link
Author

jisaacks commented Aug 3, 2021

@jcalz gotcha thanks, I'll close it then.

@jisaacks jisaacks closed this as completed Aug 3, 2021
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

3 participants