-
Notifications
You must be signed in to change notification settings - Fork 12.8k
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
noUncheckedIndexedAccess with enums could be type narrowed #47508
Comments
Can be worked around with |
Your example is very narrow. Here's another example where it wouldn't work:
|
Yip it was intentionally narrow to demonstrate a scenario where I believe it shouldn't produce an undefined? |
And I demonstrated why it should produce |
I think the issue here is that numeric enums' reverse mappings are not strongly typed. One could imagine a stronger typing where you wouldn't care about index signatures at all (why would you want to index into an enum with an arbitrary number anyway? It's not like TS implements reverse bit flags): ⚙🛠const _Meat = { Sausage: 0, Bacon: 1 } as const;
function withReverse<T extends Record<keyof T, PropertyKey>>(
obj: T): T & { [K in keyof T as T[K]]: K } {
return Object.assign({}, obj,
Object.fromEntries(Object.entries(obj)
.map(([k, v]) => ([v, k]))));
}
const Meat = withReverse(_Meat);
namespace Meat {
export type Sausage = typeof Meat.Sausage;
export type Bacon = typeof Meat.Bacon;
}
type Meat = typeof Meat[keyof typeof _Meat] const sausage = Meat.Sausage // 0
const value = Meat[sausage] // "Sausage" As such this feels like it's strongly related to #38806 |
In this case |
@RyanCavanaugh Counterpoint: enum Meat {
Sausage,
Bacon
}
const sausage: Meat.Sausage = 42;
const value = Meat[sausage] // string | undefined
console.log(value); // indeed, undefined Numeric enums are weird. |
Sure, but all the unsoundness is packed into the assignment from const sausage: Meat.Sausage = 42;
const zero: 0 = sausage;
const tup = [1, 1] as const;
const n: number = tup[zero]; |
Huh, that’s bizarre. So |
Bug Report
Hi, we're trying to tighten up some of our code by using
noUncheckedIndexedAccess
. I know there are caveats to this compiler option which we've found by searching, but this one feels more like a bug?🔎 Search Terms
Searched a variety of issues, the most relevant being: #13778
🕗 Version & Regression Information
4.5.4
⏯ Playground Link
💻 Code
🙁 Actual behavior
value
in the above example can't be undefined🙂 Expected behavior
value
to be typed as string, notstring | undefined
The text was updated successfully, but these errors were encountered: