![](/img/trans.png)
[英]Typescript: Type 'Element[]' is not assignable to type 'ReactElement<any, string | JSXElementConstructor<any>>'
[英]Argument of type 'Element' is not assignable to parameter of type 'ReactElement<any>
這段代碼:
import * as React from 'react';
const Component = () => <div/>;
function culprit<P>(node: React.ReactElement<P>) {
console.log(node);
}
culprit(<Component/>);
...在使用 TypeScript 編譯時產生此編譯錯誤:
錯誤 TS2345:“Element”類型的參數不可分配給“ReactElement”類型的參數。 類型“null”不可分配給類型“ReactElement”
只有當strictNullChecks TypeScript 編譯標志設置為true
時才會發生這種情況。
是的,我可以禁用該標志,但我希望啟用它以增加編譯時檢查/安全性。
如果我將最后一行更改為:
culprit( (<Component/> as React.ReactElement<any>) );
...它適用於設置為true
的標志。
我最近嘗試在 React 項目中從“純”JavaScript 遷移到 TypeScript,這會阻礙我的所有測試,因此將所有 TypeScript 類型斷言添加到測試代碼中的所有這些事件將是一件痛苦的事情。
這是一個錯誤,還是我別無選擇?
如果您的組件或組件測試文件中有 JSX,則必須將.tsx
作為文件擴展名。 我的代碼沒有編譯,因為我有 .ts 文件擴展名。 我將它重命名為.tsx
/ jsx
那jsx
它開始工作得很好!
另請注意,我使用的是 Typescript,這就是我將其重命名為.tsx
的原因。 如果您使用 ES6, .jsx
其重命名為.jsx
。
這顯然是 15.0.5 React 類型定義中引入的一個問題。 如果您更改為 15.0.4,一切都應該沒問題。
看到這個問題: https : //github.com/DefinitelyTyped/DefinitelyTyped/pull/14284
當我不在 React Fragment 或空標簽中返回 JSX 時,就會發生這種情況。
const ErrorMessage: FC<ErrorProps> = (props) => {
if (!isEmpty(props.errors)) {
return Object.entries(props.errors).map((item) => (
<Typography component="span">{item[0]}</Typography>
))
};
return <></>;
};
當我添加空標簽時,一切都按預期工作。
const ErrorMessage: FC<ErrorProps> = (props) => {
if (!isEmpty(props.errors)) {
return (
<>
{Object.entries(props.errors).map((item) => (
<Typography component="span">{item[0]}</Typography>
))}
</>
)
};
return <></>;
};
此外,如果我們刪除return <></>
語句,則會顯示錯誤。 正如我所寫,組件總是需要返回正確的 JSX 組件。
版本
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.