typescript - 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,
},
]
它可以工作,但我不确定这是一个好的解决方案。
解决方案
为清晰而创建一个新变量并不是最糟糕的解决方案,如果你想简化它,你也可以这样做。
const columns = [
{
title: 'State',
dataIndex: 'state',
render: (text: any) => <a>{text}</a>,
align: 'right' as AlignType,
}
您可以在此处阅读有关“as”运算符的更多信息
推荐阅读
- programming-languages - 上下文无关语法设计 - 为什么不允许这样做?
- sql - 获取保存在多行中的相应代码
- docker - Rancher中启动pod后如何注册gitlab runner
- html - css 悬停返回过渡
- mysql - 带有多个 SELECT 语句的 SQL IF ELSE
- javascript - 我尝试使用 selenium java 一个一个地打开多个链接,但是在做时我得到了陈旧的元素引用异常
- amazon-web-services - AWS 应用程序负载均衡器:503 网关超时
- java - 我想为长值创建一个线程安全的
- c++ - 在 VS 代码中调试时无法打开“osteram.tcc”和“ios_base.h”
- python-3.x - 是否存在类似followin的东西?('''select * from TABLE where ? in FIELD''',(VAR))