Jor*_*nur 2 lint typescript reactjs eslint
Don't use `{}` as a type. `{}` actually means "any non-nullish value".使用 React 和 TypeScript 时,我的 Contact 组件出现 ESlint 错误。
该组件没有任何道具。
export default class Contact extends React.Component<{}, MyState> {
constructor(props = {}) {
super(props);
this.state = {
signedUp: false,
};
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试使用null,但这引发了其他 ESLint 错误。
扩展 Jordan 答案,将此规则仅应用于.eslintrc.js文件添加中的 React 组件
overrides: [
{
// Apply rule override only to files with the following extensions
files: ['*.tsx', '*.jsx'],
rules: {
'@typescript-eslint/ban-types': [
'error',
{
extendDefaults: true,
types: {
'{}': false,
},
},
],
},
},
]
Run Code Online (Sandbox Code Playgroud)
我强烈不同意所选答案是正确的。此警告的存在是有原因的;对于任何用谷歌搜索它的人,我将把它保留为 ESLint 所说的:
- 如果您想要一种含义为“任何对象”的类型,您可能需要
Record<string, unknown>改为。- 如果您想要一个表示“任何值”的类型,您可能需要
unknown改为。- 如果您想要一个表示“空对象”的类型,您可能需要
Record<string, never>改为。
经过大量挖掘,我发现了以下 GitHub 问题。
通过向您添加以下内容,您.eslintrc.js可以忽略该规则。建议使用Configurations使此规则仅适用于 React 组件。这将确保其他地方的强类型。
"rules": {
"@typescript-eslint/ban-types": [
"error",
{
"extendDefaults": true,
"types": {
"{}": false
}
}
]
}
}
Run Code Online (Sandbox Code Playgroud)
来源:https : //github.com/typescript-eslint/typescript-eslint/issues/2063#issuecomment-675156492
| 归档时间: |
|
| 查看次数: |
1352 次 |
| 最近记录: |