【问题标题】:How I suppress a TS2322 warning in WebStorm?如何在 WebStorm 中抑制 TS2322 警告?
【发布时间】:2019-12-17 14:14:02
【问题描述】:

我在 WebStorm 中有一个使用 expo init 创建的项目,并将 IDE 配置为使用 ESLint 和 @typescript-eslint 并启用“Typescript 语言服务”(并禁用 TSLint)。

如果我替换下面的代码App.tsxwith 的内容,我会在 IDE 的编辑器中突出显示许多检查错误。我可以(如预期的那样)消除其中的大部分

/* eslint-disable @typescript-eslint/explicit-member-accessibility, @typescript-eslint/no-use-before-define, @typescript-eslint/explicit-function-return-type */

但有些错误仍然存​​在,尤其是

Apprender 中的每个Component 相关联。正如预期的那样,我也可以通过禁用“Typescript Language Service”来禁用这些错误,但不能(尽管 IDE 建议这样做)@ts-ignore(在任何范围内)。

唯一有效的方法是替换

class Counter extends Component

class Counter extends Component<any>

在我的项目中抑制TS2322 错误的正确方法是什么?为什么使用&lt;any&gt; 有效(我应该使用它),为什么@ts-ignore 没有效果?


import React, { Component } from 'react'
import { View, Text, StyleSheet } from 'react-native'

class Counter extends Component {

  state = {count: 0}

  componentDidMount() {
    setInterval(() => {
      this.setState({count: this.state.count + 1})
    }, 1000)
  }

  render() {
    const {count} = this.state
    const {color, size} = this.props

    return (
      <Text style={{color, fontSize: size}}>
        {count}
      </Text>
    )
  }
}

export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Counter color={'lightblue'} size={16} />
        <Counter color={'skyblue'} size={32} />
        <Counter color={'steelblue'} size={80} />
        <Counter color={'darkblue'} size={140} />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
})

【问题讨论】:

    标签: typescript react-native webstorm eslint


    【解决方案1】:

    您可以将@ts-ignore 放在 JSX 中组件的正上方以抑制它,例如:

      {/* 
      // @ts-ignore */}
      <Counter color={'lightblue'} size={16} />
    

    (见https://github.com/Microsoft/TypeScript/issues/27552。)

    但我强烈建议您以typescript 的方式重新编写您的组件以消除编译器错误,例如:

    interface IProps {
        color: string;
        size: number;
    }
    
    interface IState {
        count: number;
    };
    
    export default class Counter extends Component<IProps, IState> {...}
    

    【讨论】:

    • 太棒了!虽然第一个解决方案不起作用(// @ts-ignore 被渲染或在渲染时产生致命错误),但第二个解决方案完美。
    猜你喜欢
    • 2014-12-23
    • 2019-02-25
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2021-06-03
    相关资源
    最近更新 更多