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?
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?
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
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
".