[英]How to handle optional property that has a value in defaultProps?
I got the following class component:我得到以下 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";
}
}
Why is this.props.optional.length
causing an error?为什么
this.props.optional.length
导致错误? I'm using TS 4.3 and React v17, I thought that this issue was fixed in 3.0 in this PR: https://github.com/microsoft/TypeScript/issues/23812 (see the second block of code) Or am I misunderstanding this fix, its just for fixing this issue in JSX code?我正在使用 TS 4.3 和 React v17,我认为这个问题在这个 PR 的 3.0 中得到了修复: https://github.com/microsoft/TypeScript/issues/23812 (参见第二段代码)或者我误解了这个修复,只是为了修复 JSX 代码中的这个问题?
If possible I would not make the optional
prop required, I think this would confuse users who are instantiating the prop object (why is a prop required when its optional?)如果可能的话,我不会让
optional
道具成为必需的,我认为这会让正在实例化道具 object 的用户感到困惑(为什么在可选道具时需要道具?)
In order to make it work, you should make your optional
property required.为了使其工作,您应该使您的
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
See, there is no error.看,没有错误。 TS is able to figure out that
static defaultProps
will assure that optional
prop will always be a non empty string TS 能够计算出
static defaultProps
将确保optional
prop 始终为非空字符串
It turns out that this is not supported as of TypeScript 4.3.5.事实证明,自 TypeScript 4.3.5 起不支持此功能。
There are some workarounds, but for me they either come with downsides or are way too complex: https://github.com/microsoft/TypeScript/issues/30251有一些解决方法,但对我来说,它们要么有缺点,要么太复杂: https://github.com/microsoft/TypeScript/issues/30251
We have decided to leave optional props optional even if they have a defaultProps
value, and in the code we use the ?
我们已经决定将可选道具保留为可选,即使它们具有
defaultProps
值,并且在代码中我们使用?
operator and do null/undefined checks -- this also takes care of the case that the user sets the value to undefined
or null
运算符并执行 null/undefined 检查——这也会处理用户将值设置为
undefined
或null
的情况
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.