【问题标题】:Why does naming an interface 'Props' not give correct type-checking with a functional component? (typescript & react-native)为什么将接口命名为“道具”不能对功能组件进行正确的类型检查? (打字稿和反应原生)
【发布时间】:2019-05-02 04:43:33
【问题描述】:
  • tslint-microsoft-contrib 版本:^5.2.1
  • TSLint 版本:^5.11.0
  • TypeScript 版本:^3.1.6
  • 通过运行 TSLint:VS 代码

TypeScript 代码被检查

import * as React from 'react'
import { View } from 'react-native'

interface Props {
  name: string
  color: string
  price: string
}

const Card = ({ name, color, price }: Props) => (
  <View style={{ backgroundColor: color }} />
)

export default Card

使用tslint.json 配置:

{
  "defaultSeverity": "error",
  "extends": [
    "tslint:recommended",
    "tslint-config-standard",
    "tslint-react",
    "tslint-config-prettier"
  ],
  "jsRules": {},
  "rulesDirectory": ["node_modules/tslint-microsoft-contrib"],
  "rules": {
    "ordered-imports": false,
    "object-literal-sort-keys": false,
    "member-ordering": false,
    "jsx-no-lambda": false,
    "jsx-boolean-value": false,
    "interface-name": false,
    "semicolon": false,
    "react-unused-props-and-state": [
      true,
      { "props-interface-regex": "Props$", "state-interface-regex": "State$" }
    ]
  }
}

实际行为

Typescript 没有发现组件中已使用颜色属性这一事实,并在接口级别报告:[tslint] Unused React property defined in interface: color [react-unused-props-and-state]

但是,如果功能组件更改为类组件,或者简单地说,如果接口被命名为 Props 以外的其他名称,例如CardProps - 它按预期获取属性的使用情况。

预期行为

我希望编译器能够了解该属性正在组件内使用这一事实,就像在上面提到的其他场景中一样。

【问题讨论】:

  • @ShaunLuttin 对,编译器没有注意到这一点。它仍然显示未使用的颜色。
  • 抱歉,我明白了困惑的所在。我已经更新了上面的代码示例以反映实际错误。我最初使用名称prop时复制错误后将代码更改为颜色。

标签: reactjs typescript react-native visual-studio-code tslint


【解决方案1】:

不幸的是,这是 tslint-microsoft-contrib 的一个已知问题。 react-unused-props-and-state 规则不适用于无状态功能组件 (SFC)。一种解决方法是改用有状态组件(类)。

https://github.com/Microsoft/tslint-microsoft-contrib/issues/339

【讨论】:

  • 不幸的是,这似乎是正确的答案。我已经在 repo 上提出了一个问题,并在该线程中进行了回复。谢谢肖恩。
猜你喜欢
  • 2021-05-04
  • 2020-01-02
  • 2021-04-20
  • 2020-01-15
  • 1970-01-01
  • 2023-04-02
  • 2019-03-14
  • 2021-12-09
  • 2023-02-07
相关资源
最近更新 更多