[英]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 檢查——這也會處理用戶將值設置為undefined
或null
的情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.