TypeScript+React项目使用AntD Notification时类型索引报错如何解决?
报错截图:
报错原因
元素隐式具有 "any" 类型,因为类型为 "any" 的表达式不能用于索引类型 "NotificationApi"。
该报错的核心原因是openNotificationWithIcon的入参type被声明为any类型,TypeScript无法验证该值是否是NotificationApi类型的合法属性,因此不允许用该值直接索引notification对象。
解决方案
最优方案是给type添加精确的类型注解,限制入参只能是notification对象支持的合法方法名,修改后的完整代码如下:
import { Button, notification, Row, Col, Card } from "antd"; import React, { FC } from "react"; export const NotificationExample: FC = () => { // 仅需修改这一行的入参类型,把any替换为keyof typeof notification const openNotificationWithIcon = (type: keyof typeof notification): void => { notification[type]({ duration: 0, message: "Notification Title", description: "This is the content of the notification. This is the content of the notification. This is the content of the notification.", }); }; return ( <Card type="inner" title="Notification" bodyStyle={{ padding: "32px 32px 16px 32px" }} extra={ <Button icon="external-link-alt" target="_blank"> AntDesign </Button> } > <Row gutter={[32, 32]}> <Col span={24}> <div className="divider">Types</div> <Button onClick={() => openNotificationWithIcon("open")} className="margin-right-md"> Default </Button> <Button onClick={() => openNotificationWithIcon("success")} className="margin-right-md"> Success </Button> <Button onClick={() => openNotificationWithIcon("info")} className="margin-right-md"> Info </Button> <Button onClick={() => openNotificationWithIcon("warning")} className="margin-right-md"> Warning </Button> <Button onClick={() => openNotificationWithIcon("error")}>Error</Button> </Col> </Row> </Card> ); };
方案说明
keyof typeof notification会自动提取notification对象所有公开方法名组成联合类型'open' | 'success' | 'info' | 'warning' | 'error',既可以从源头限制入参只能传合法值,传入非法值时TS会直接给出类型提示,也能通过TS的类型校验消除索引报错。
如果只需要临时修复报错,也可以在索引时添加类型断言即可:
notification[type as keyof typeof notification]({ /* 通知配置项 */ })
内容的提问来源于stack exchange,提问作者Amine Aamer
相关产品推荐
相关产品推荐

