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:
CodePudding user response:
You need to type const columns
as DataTableHeader[]
, otherwise it implicitly gets the type ({ key: string; label: string; align?: undefined; } | { align: string; key: string; label: string; })[]
.
const columns: DataTableHeader[] = [ ... ]
Note that you will also get errors if you try to add in invalid object in this assignment due to that type:
const columns: DataTableHeader[] = [
{
// Type '"wrong"' is not assignable to type '"right" | "inherit" | "left" | "center" | "justify" | undefined'.
// |
// v
align: "wrong",
key: "costPrice",
label: "Cost Price",
}
]
CodePudding user response:
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'
}
];