TS2322 Type 'string' is not assignable to type '"left" | "center" | "right" | undefined'

Viewed 3709

I am new with Typescript. I use ant design version 4.0 and I want add align property to my column, but at columns attribute of Table it show this error. I know I should match the type of the variable with AlignType but I dont know how exactly to do this. Thank you guys in advance.

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: I add new variable

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

and it work but I am not sure this is good solution.

1 Answers

Creating a new variable for clarity isn't the worst solution, you could also if you wanted to streamline it do something like this.

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

You can read more about the 'as' operator here

Related