繁体   English   中英

如何处理在 defaultProps 中有值的可选属性?

[英]How to handle optional property that has a value in defaultProps?

我得到以下 class 组件:

type Props = {
    required: string;
    optional?: string;
};

class TestComp extends Component<Props> {
  static defaultProps = {
    optional: "dff"
  }
    render() {
    // ERROR: Object is possibly 'undefined'.
    this.props.optional.length
    return "abcd";
  }
}

为什么this.props.optional.length导致错误? 我正在使用 TS 4.3 和 React v17,我认为这个问题在这个 PR 的 3.0 中得到了修复: https://github.com/microsoft/TypeScript/issues/23812 (参见第二段代码)或者我误解了这个修复,只是为了修复 JSX 代码中的这个问题?

如果可能的话,我不会让optional道具成为必需的,我认为这会让正在实例化道具 object 的用户感到困惑(为什么在可选道具时需要道具?)

游乐场链接

请看这条评论

为了使其工作,您应该使您的optional属性成为必需的。

import React, { Component } from 'react'

type Props = {
    required: string;
    optional: string;
};

class TestComp extends Component<Props> {
    static defaultProps = {
        optional: "dff"
    }
    render() {
        // ERROR: Object is possibly 'undefined'.
        this.props.optional.length
        return "abcd";
    }
}
const x = <TestComp required="sdf" /> // no error

看,没有错误。 TS 能够计算出static defaultProps将确保optional prop 始终为非空字符串

操场

事实证明,自 TypeScript 4.3.5 起不支持此功能。

有一些解决方法,但对我来说,它们要么有缺点,要么太复杂: https://github.com/microsoft/TypeScript/issues/30251

我们已经决定将可选道具保留为可选,即使它们具有defaultProps值,并且在代码中我们使用? 运算符并执行 null/undefined 检查——这也会处理用户将值设置为undefinednull的情况

暂无
暂无

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

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