0
let x = { a: 1, b: "2" } 
x.c = 3 // this throws an error (c is not assignable to {a: number, b: "string" })

is there a simple way to resolve this error without using the any type or defining types?

  • 1
    What do you mean by "defining types"? Is `let x: {a: number, b: string, c?: number} = {a: 1, b: "2"}` "defining" a type? I'm mentioning one but not declaring it. And if you can't mention a type then I'm not sure what you're looking for; could you [edit] to elaborate on your criteria? – jcalz Jul 27 '23 at 13:00
  • Does this answer your question? [How do I dynamically assign properties to an object in TypeScript?](https://stackoverflow.com/questions/12710905/how-do-i-dynamically-assign-properties-to-an-object-in-typescript) – Alejandro Jul 27 '23 at 13:20
  • @berse2212 jcalz's comment is far from "the only correct answer". For example, it suggests without any good reason that `c` is optional. Judging by the code, it might not be. – Parzh from Ukraine Jul 27 '23 at 14:03
  • I need more info from the OP before I can even begin to know what *a* correct answer is, let alone *the* correct answer. – jcalz Jul 27 '23 at 14:06

1 Answers1

0

You're not giving TypeScript the information about the type of x, so it has to infer the type from what it's got. What it's got is { a: 1, b: "2" }, so it infers x to be { a: number, b: string }. There's no property c here, thus you get an error when you try to assign something to x.c.

To fix this, you have to provide the type explicitly, rather than forcing TypeScript to infer it. This is what you can do:

interface Thing {
  a: number
  b: string
  c: number
}

const x = { a: 1, b: "2" } as Thing
x.c = 3

Try it.

Note that const x: Thing = { … } won't work. That's because this syntax means "x can only be assigned a value that has properties a, b, and c". So, if you try to assign to it an object without property c, it would be a constraint violation and an error.

The syntax const x = { … } as Thing means "the object might look like it has some properties and values, but I know for certain that it is actually Thing".

Parzh from Ukraine
  • 7,999
  • 3
  • 34
  • 65