TS2322 类型"字符串"不可分配给类型 ' "left" | "center" | "right" |未定义'



我是Typescript的新手。我使用的是ant设计4.0版本,我想将align属性添加到我的列中,但在表的columns属性中显示了这个错误。我知道我应该用AlignType匹配变量的类型,但我不知道该怎么做。提前谢谢大家。

interface ColumnSharedType<RecordType> {
title?: React.ReactNode;
key?: Key;
className?: string;
fixed?: FixedType;
onHeaderCell?: GetComponentProps<ColumnsType<RecordType>[number]>;
ellipsis?: boolean;
align?: AlignType;
}
export interface ColumnGroupType<RecordType> extends ColumnSharedType<RecordType> {
children: ColumnsType<RecordType>;
}
export declare type AlignType = 'left' | 'center' | 'right';
const columns = [
{
title: 'State',
dataIndex: 'state',
render: (text: any) => <a>{text}</a>,
align: 'left', // it need type AlignType 
},
]
return (
<Table className="state__table" columns={columns} dataSource={data}/>
// TS2322 Type 'string' is not assignable to type '"left" | "center" | "right" | undefined'.
)

ps:我添加了新的变量

const right: AlignType = 'right';
const columns = [
{
title: 'State',
dataIndex: 'state',
render: (text: any) => <a>{text}</a>,
align: right,
},
]

它是有效的,但我不确定这是一个好的解决方案。

创建一个新的变量并不是最糟糕的解决方案,如果你想简化它,你也可以这样做。

const columns = [
{
title: 'State',
dataIndex: 'state',
render: (text: any) => <a>{text}</a>,
align: 'right' as AlignType,
}

你可以在这里阅读更多关于"as"运营商的

const columns = [
{
title: "time",
dataIndex: "time",
width: "20%",
editable: false,
align: "center", 
// 修改为  align: "center" as "center",
onCell: (record: RowSpanData) => {
return {
rowSpan: record.rowSpan,
};
},
},]

最新更新