reactjs - React-Typescript : How do I type a default prop?

标签 reactjs typescript

假设我有这个组件类:

interface SomeComponentProps {
  someOptionalProperty?: string;
}
interface SomeComponentState { /* ... */ }

class SomeComponent extends React.Component<SomeComponentProps, SomeComponentState> {
  static defaultProps = {
    someOptionalProp = 'some default value',
  }

  method() {
    const shouldNotBeOptional = this.props.someOptionalProp;
  }
}

如何断言 this.props.someOptionalProp 在类中不是未定义的,而且在尝试使用组件时也是可选的?

我一直在做的只是通过创建 getter 来完全忽略 defaultProps

return `this.props.someOptionalProp || 'the default value'`;

但我想使用 defaultProps 因为我的团队使用它。

最佳答案

此问题已在 here 中讨论并解决。 。现在您只需这样做:

interface Props {
  thing: string; // note: not optional within class, but is optional when writing due to the default
}

class Thing extends React.Component<Props> {
   static defaultProps = {
      thing: 'hello'
   }

  render() {
    console.log(this.props.thing) // strict type from `Props`
    // ...
 }
}
// ..
<Thing /> // works, thanks to `defaultProps`

它适用于 Typescript 3.1.6 和 React 16.5.0

关于reactjs - React-Typescript : How do I type a default prop?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50272065/

相关文章:

TypeScript——一些高级类型推断的问题;尝试为 Rematch 构建更好的类型

javascript - 如何通过 typescript 声明具有两种类型的变量

javascript - 如何编辑对象并将新对象传递给数组? ReactJS, Material UI

javascript - 不变违规 : View config not found for name div

javascript - 登录后在哪里以及如何更改 session 用户对象?

javascript - 无法刺激模态 : React-Redux 中输入的变化

c# - .NET TypeScript 解析器到 AST

node.js - 如何处理来自 create-react-app 的弃用消息?

typescript 使用装饰器获取参数的值

javascript - 如果自上次运行以来没有任何变化,TSLint 是否有阻止运行的选项?