I have a .ts file and I want to use the following type definition:
type MyType = {
status: "ACTIVE" | "INACTIVE"
}
When I use this type for a variable which I directly set value, everything is good:
const myObj1: MyType = {
status: "ACTIVE"
}
But if I use a variable to set the value I get an error:
const data = {
status: "ACTIVE"
}
const myObj2: MyType = data
Error:
Type '{ status: string; }' is not assignable to type 'MyType'.
Types of property 'status' are incompatible.
Type 'string' is not assignable to type '"ACTIVE" | "INACTIVE"'.
You can try it on here
I tried different options (like this), but the problem is that my types are generated from Json Schemas and I can't edit the generated files.
CodePudding user response:
This is because status
in data
is infered as a string
whereas MyType
expects it to be either "ACTIVE"
or "INACTIVE"
.
You need just to use as const
assertion
type MyType = {
status: "ACTIVE" | "INACTIVE"
}
const myObj1: MyType = {
status: "ACTIVE"
}
const data = {
status: "ACTIVE"
} as const
const myObj2: MyType = data
Or you can use new satisfies
keyword which is available in TS 4.9
type MyType = {
status: "ACTIVE" | "INACTIVE"
}
const myObj1: MyType = {
status: "ACTIVE"
}
const data = {
status: "ACTIVE"
} satisfies MyType