#indexing errors even though it should be guarded

5 messages · Page 1 of 1 (latest)

night galeBOT
#
ktibow#0

Preview:ts const flags = ["A", "B", "a", "b"] const weights = { a: 1, b: 2, c: 1, d: 1, } const value = flags.reduce( (a, b) => a + (b in weights ? weights[b] : 0), 0 )

inner comet
#

@left torrent in does not narrow the string on the left hand side because objects can have more properties than TS knows about.

#

You could:

  1. Just cast to make the error go away, b in weights ? weights[b as keyof typeof weights]
  2. Make a custom type-guard function:
const isWeightsKeys = (x: string): x is keyof typeof weights => x in weights;

or you can 'loosen' the type on weights:

const weights: Record<string, number | undefined> = {
    a: 1,
    b: 2,
    c: 1,
    d: 1,
}
const value = flags.reduce((a, b) => a + (weights[b] ?? 0), 0)
#

The last one is a good solution, except that you'll then have to null check all accesses, e.g. weights.a will be number | undefined (even though we really know it's defined)

left torrent
#

!resolve