【问题标题】:Typescript defaultProps not checking typeTypescript defaultProps 不检查类型
【发布时间】:2018-11-28 09:20:49
【问题描述】:

我正在使用 TypeScript 3.0 并根据来自 https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html 的文档

使用static defaultProps: Pick<Props, "name">; 作为显式类型 代替注释,或者不添加类型注释,如 上面的例子。

但是,如果我写:

import React, { Component } from 'react';

interface Props {
  counter: number;
}

export default class NumberCounter extends Component<Props> {
  static defaultProps = {
    counter: "i am not a number"
  };

  render() {

    return (
      <div>{this.props.counter}</div>
    );
  }
}

它可以编译并且可以工作,显然 prop 的默认值没有经过类型检查。尽管如此,当我尝试错误地使用该组件时:

<NumberCounter 
  counter="still not a number"
/>

它显示错误,并且在其他地方使用时会正确进行类型检查。这是 TypeScript 的已知错误吗?

【问题讨论】:

标签: reactjs typescript react-props


【解决方案1】:

您应该将类​​型分配给defaultProps,而不仅仅是组件本身:

static defaultProps: Props = {
    counter: "i am not a number"
};

【讨论】:

  • 它在 TypeScript 3.0 中对你有用吗?我使用这种方法遇到的问题是,如果我只想为我的一些道具分配默认值,TypeScript 会抛出一个错误,要求我为Props 接口中定义的所有属性分配默认值。跨度>
  • 在这种情况下,你可以做 defaultProps: Partial&lt;Props&gt; 并在 Props counter?: string; 中创建计数器
  • 也不行。我链接的文档中提到了这个问题:The default-ed properties are inferred from the defaultProps property type. If an explicit type annotation is added, e.g. static defaultProps: Partial&lt;Props&gt;; the compiler will not be able to identify which properties have defaults (since the type of defaultProps include all properties of Props).
猜你喜欢
  • 2021-11-14
  • 1970-01-01
  • 2012-09-29
  • 2015-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
相关资源
最近更新 更多