在 React 项目中调用 TypeScript 函数时出现此错误。
const handleLanguageChange = React.useCallback((eventKey: eventKey) => {
setLanguage(eventKey);
if(eventKey == "DE")
setCurrency("€ EUR");
else if(eventKey == "JP")
setCurrency("¥ JPY");
else if(eventKey == "US")
setCurrency("$ USD");
else
setCurrency("£ GBP");
const language = eventKey;
changeLang(language); >> ERROR HERE!
}, []);
function changeLang(language: string) {
i18n.changeLanguage(language, (err, t) => {
if (err) {
localeChangeHandlerMetric.setFailure();
} else {
localeChangeHandlerMetric.setSuccess();
}
localeChangeMetricsPublisher.publish(localeChangeHandlerMetric);
});
}
这是我得到的错误:
src/components/navigation/LanguageNav.tsx:44:22
TS2345: Argument of type 'eventKey' is not assignable to parameter of type 'string'.
Type 'null' is not assignable to type 'string'.
42 | setCurrency("£ GBP");
43 | const language = eventKey;
> 44 | changeLang(language);
| ^^^^^^^^
45 | }, []);
46 |
47 | function changeLang(language: string) {
知道我该如何处理吗?我尝试向 eventKey 添加可选类型,但没有成功。
答案 0 :(得分:1)
你 changeLang(language: string) 接收语言作为字符串类型。但是您将语言作为 eventKey 类型传递。你可以做的一些选择
选项 1: 更改 eventKey 的类型
const handleLanguageChange = React.useCallback((eventKey: string) => {
setLanguage(eventKey);
if(eventKey == "DE")
setCurrency("€ EUR");
else if(eventKey == "JP")
setCurrency("¥ JPY");
else if(eventKey == "US")
setCurrency("$ USD");
else
setCurrency("£ GBP");
const language = eventKey;
changeLang(language);
}, []);
选项 2:使用“as”关键字输入断言
const handleLanguageChange = React.useCallback((eventKey: eventKey) => {
setLanguage(eventKey);
if(eventKey == "DE")
setCurrency("€ EUR");
else if(eventKey == "JP")
setCurrency("¥ JPY");
else if(eventKey == "US")
setCurrency("$ USD");
else
setCurrency("£ GBP");
const language = eventKey as unknown as string;
changeLang(language);
}, []);
选项 3:忽略它
const handleLanguageChange = React.useCallback((eventKey: eventKey) => {
setLanguage(eventKey);
if(eventKey == "DE")
setCurrency("€ EUR");
else if(eventKey == "JP")
setCurrency("¥ JPY");
else if(eventKey == "US")
setCurrency("$ USD");
else
setCurrency("£ GBP");
const language = eventKey;
//@ts-ignore
changeLang(language);
}, []);