Pablo
Pablo

Reputation: 10602

Typescript: Code looks the same, but it's generating an error

I have an interface like this:

  interface Product {
    [key: string]: {
      options?: Record<string, string>
    }
  }

so:

  state: Product
  ...
  state = state ?? {}
  state[sku] = state[sku] ?? {}
  state[sku].options = state[sku].options ?? {}
  state[sku].options[id] = e.target.value       // this line breaks

The line highlighted above is saying that state[sku].options could be undefined, of course I know is not undefined, since I'm checking on the line before.

However, this code does exactly the same, and works.

  const newState = state ?? {}
  const slice = newState[sku] ?? {}
  slice.options = slice.options ?? {}
  slice.options[id] = e.target.value

so, what am I missing?

Upvotes: 2

Views: 53

Answers (1)

marzelin
marzelin

Reputation: 11600

Its a limitation of Typescript. If you create a type like below:

type T = { [key: string]: string | undefined };

And then try:

var sth: T = { prop: "abc" };
sth.prop.slice()

you'll get an error since the definition of sth will still be general T. It doesn't care that one of props of sth is actually a string (that is, typescript won't constrain the type of sth).

But when you do:

var u = { prop: "abc" };
u.prop.slice()

The type of u will be constrained to

{
  prop: string
}

so no error here.

Upvotes: 2

Related Questions