#object[keyof object] has type `never`?

11 messages · Page 1 of 1 (latest)

topaz pagoda
#

I thought this worked... what am I doing wrong?

interface State {
  one: string;
  two: number;
}

declare const key: keyof State;
declare const state: State;

const value = {
  one: "",
  two: 0
}[key]

state[key] = value;
// Type 'string | number' is not assignable to type 'never'.
//  Type 'string' is not assignable to type 'never'.(2322)

I expected state[key] to be string | number not never

smoky sparrow
topaz pagoda
#

Interesting...

#

So... what should I do in this case? Open to radically different code approach.

topaz pagoda
#

Don't love it and its still not strictly speaking type safe but did this

const setState = <K extends keyof State>(key: K, state: State, fromValues: State) {
  state[key] = fromValues[key];
}

setState(key, state, {
  one: "",
  two: 0
});
calm pollen
topaz pagoda
#

The actual code uses a Redux reducer map that generates the values (so a different function for every state key that takes the previous state key value and an action and returns a new state key value), not a plain object, but the same type issue on assignment of the state key is in play.

calm pollen
#

is there a way you can set it up to create a new object rather than mutating an existing one? that may make your life easier. i don't use redux so i can't speak to the specifics there, but i thought it was pretty FP-ish so mutating an argument like that might be unexpected

#

IIUC you have something like { a: A, b: B } and functions for A => A1 and B => B1 and want to apply them to end up with { a: A1, b: B1 }?

flint zealot
#

Nowadays the Redux standard is to use immer which uses mutable-like code but produces immutable updates under the hood.