简体   繁体   English

Typescript defaultProps不检查类型

[英]Typescript defaultProps not checking type

I'm using TypeScript 3.0 and according to the documentation from https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html 我正在使用TypeScript 3.0,并根据https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html中的文档进行操作

Use static defaultProps: Pick<Props, "name">; 使用static defaultProps: Pick<Props, "name">; as an explicit type annotation instead, or do not add a type annotation as done in the example above. 作为显式类型注释,或者不像上面的示例一样添加类型注释。

However if I write: 但是,如果我写:

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>
    );
  }
}

It compiles and works, apparently the prop's default value isn't typechecked. 它可以编译和工作,很明显,prop的默认值没有经过类型检查。 Nonetheless, when I try to use the component erroneously: 但是,当我尝试错误使用组件时:

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

It shows an error, and typechecks correctly when it is used elsewhere. 它显示错误,并在其他地方使用时正确检查类型。 Is this a known bug with TypeScript? 这是TypeScript的已知错误吗?

You should have a type assigned to defaultProps not only the component itself: 您不仅应将组件本身,还应将类型分配给defaultProps

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM