Search code examples
typescripttype-level-computationmapped-types

shouldn't access to mapped types be an union with undefined?


I have a type like this:


type MyType = {
  [key:string]:number
}

const someValue = MyType.whatever // the type here should be number|undefined, but it's undefined

I mean, it's impossible for MyType to have EVERY string as key. And it seems like an unnecessary thing to do to turn it into


type MyType = {
  [key:string]:number|undefined
}

Solution

  • Unleast you have an noUncheckedIndexedAccess: true in tsconfig.json, typescript allows you to acess arrays and records without checks:

    let a = [1, 2, 3]
    let a5 = a[5] // number
    //  ^?
    
    let o: Record<string, number> = {a: 123}
    let ob = o.b // number
    //  ^?
    

    This is made because generally you would check for undefined yourself if you would expect it to be a possibly invalid key

    If you wand a record with optional keys (to enforce user to check them), define it yourself

    let o1: Partial<Record<string, number>> = {};
    let o2: {[key: string]?: number} = {}