首页 > 解决方案 > TS2322 类型“字符串”不可分配给类型“左”| “中心” | “对” | 不明确的'

问题描述

我是打字稿的新手。我使用 ant design 4.0 版,我想将 align 属性添加到我的列中,但是在 Table 的 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,
    },
]

它可以工作,但我不确定这是一个好的解决方案。

标签: typescriptantd

解决方案


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

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

您可以在此处阅读有关“as”运算符的更多信息


推荐阅读