Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript : Opting-out of noUncheckedIndexedAccess on a per-case basis

Tags:

typescript

My TS code use the compiler option noUncheckedIndexedAccess which adds undefined as a possible value to all index signatures.

type Type = {[k: string]: string}
const obj: Type = {}
obj.hello // TS detects type `string | undefined`

Fine ... Now, I am defining a Proxy which returns a default value for each property, e.g. :

type Type = {[k: string]: string}

const obj: Type = {}

const p = new Proxy<Type>(obj, {
    get: (_, k) => {
        return '_' + String(k)
    },
})

p.hello // TS detects type `string | undefined`

I would like any member of the proxied object p to be typed as string instead of string | undefined (without deactivating noUncheckedIndexedAccess). Is this possible ? Something like :

type Type = {[k: string]: NonNullable<string>}
like image 521
sebpiq Avatar asked Oct 22 '25 10:10

sebpiq


1 Answers

TypeScript's index signature types were never intended to represent an object for which every possible key has a defined property value. Indeed, such a type really only makes sense for a subset of Proxy objects, and that use case isn't very common (compared to dictionary/record/array types, which is what index signatures were intended to model).

Still, when the --noUncheckedIndexedAccess compiler option is disabled, you can sort of treat an index signature as if it were such an all-properties-exist Proxy, since the possibility of undefined is ignored. If you still want that behavior when you enable that option, well, you're out of luck, at least for now. Such a feature is not part of the language.

Now, there is an open feature request for this at microsoft/TypeScript#47594 to support your use case. It wouldn't hurt for you to go there and give it a 👍. Of course, it probably wouldn't really help, either. Currently there are only a few dozen upvotes on it, so it's not anywhere near the top of the list for community-requested features. It's also listed as "Awaiting More Feedback", meaning that before they would even consider implementing it, they'd want to hear more about why the feature would be needed and why existing approaches don't work well enough. So you might want to add your use case as a comment, at least if it is different from or more compelling than those already listed. But again, I doubt it would have much of an effect.

like image 102
jcalz Avatar answered Oct 24 '25 06:10

jcalz