The same problem is asked in this question but It didn’t answer my question as to why we need to use ‘as’ to make it work:
TS2322 Type 'string' is not assignable to type '"left" | "center" | "right" | undefined'
I have the following code but it’s showing error
Type 'string' is not assignable to type '"right" | "inherit" | "left" | "center" | "justify" | undefined'
even though the value is in one of the values allowed.
interface DataTableHeader {
key: string
label: string
align?: "right" | "inherit" | "left" | "center" | "justify"
}
const columns = [
{
key: "title",
label: "Title",
},
{
align: "right",
key: "costPrice",
label: "Cost Price",
}
]
const DataTable = (columns?: DataTableHeader[]) => {
return columns
}
DataTable(columns) // here
// Errors in code
Argument of type '({ key: string; label: string; align?: undefined; } | { align: string; key: string; label: string; })[]' is not assignable to parameter of type 'DataTableHeader[]'.
Type '{ key: string; label: string; align?: undefined; } | { align: string; key: string; label: string; }' is not assignable to type 'DataTableHeader'.
Type '{ align: string; key: string; label: string; }' is not assignable to type 'DataTableHeader'.
Types of property 'align' are incompatible.
Type 'string' is not assignable to type '"right" | "inherit" | "left" | "center" | "justify" | undefined'.
>Solution :
In TypeScript, the type string is not a subtype of "right" | "inherit" | "left" | "center" | "justify" | undefined. This means that a value of type string cannot be assigned to a variable with a type of "right" | "inherit" | "left" | "center" | "justify" | undefined.
To fix this error, you can use a type assertion to explicitly tell the TypeScript compiler that the string value is actually one of the allowed values. This can be done by using the as keyword followed by the type that you want to assert the value to be.
You can update the code like this:
const columns = [
{
key: "title",
label: "Title",
},
{
align: "right" as "right" | "inherit" | "left" | "center" | "justify",
key: "costPrice",
label: "Cost Price",
}
]
Or you can update the type of the align property in the DataTableHeader interface to be of type string, which would allow any string value to be assigned to it. This would avoid the need for a type assertion.
interface DataTableHeader {
key: string;
label: string;
align?: string;
}
const columns = [
{
key: 'title',
label: 'Title'
},
{
align: 'right',
key: 'costPrice',
label: 'Cost Price'
}
];
