[英]"Missing return type on function" for every React class method
我的 Typescript 項目中有一個有狀態的 React 組件。 我使用@typescript-eslint/parser
typescript @typescript-eslint/parser
和@typescript-eslint/eslint-plugin
用 ESLint lint 它。 我啟用了規則@typescript-eslint/explicit-function-return-type
。
我的組件看起來類似於:
interface Props = {
name: string;
}
interface State = {
score: number
}
class Person extends Component<Props, State> {
state = {
score: 2,
};
componentDidMount() {
...
}
render() {
...
}
}
在上面的組件中,我在componentDidMount
和render
方法上得到了 ESLint 錯誤:
Missing return type on function - @typescript-eslint/explicit-function-return-type
總的來說,我非常喜歡 lint 規則,但我肯定不必為所有這些 React 方法聲明返回類型。 我已經安裝了@types/react
和@types/react-dom
,所以這些返回類型不是已經涵蓋了嗎?
嘗試將渲染函數的返回類型寫為
render(): JSX.Element {
// render code
}
這對我有用!
我只是通過將規則添加到.eslintrc.json
來讓它工作
{ "allowTypedFunctionExpressions": true }
.eslintrc.json
{
"parser": "@typescript-eslint/parser",
"extends": ["plugin:@typescript-eslint/recommended"],
"plugins": ["@typescript-eslint"],
"rules": {
"@typescript-eslint/explicit-function-return-type": [
"error",
{ "allowTypedFunctionExpressions": true }
]
}
}
版本
"@typescript-eslint/eslint-plugin": "^1.10.2",
"@typescript-eslint/parser": "^1.10.2",
"eslint": "^6.0.0",
我在這里可能是錯的,因為我沒有親自使用@typescript-eslint/explicit-function-return-type
但它的名字聽起來好像你需要在每個編寫的函數中return
,包括生命周期方法。 請記住,ESLint 和 React 是不一樣的。 ESLint 只是運行你的代碼來指出潛在的錯誤。 如果不包含這些return
語句,React 庫應該仍然能夠正常運行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.