TypeScriptの別のプロパティに応じて、2つのプロパティをオプションとして設定できるかどうかを知りたいです。例:
場合message
であるundefined
私が欲しいa
とb
要求されるように、IFがmessage
あるnot undefined
私が欲しいa
とb
、オプションであることを。
この条件を強制する方法は?
type Props = Readonly<{
message?: React.ReactNode
a: React.ReactNode
b: React.ReactNode
}>
const Component = ({ message, a, b}: Props) => <div >
共用体タイプを使用して、この効果を実現できます。
type Props = Readonly<{
message?: undefined
a: string
b: string
} | {
message: string
a?: string
b?: string
}>
const Component = ({ message, a, b}: Props) => <div />;
let c = <Component message="" /> //ok
let c2 = <Component a="" b="" /> //ok
let c3 = <Component message="" b="" /> //ok
let c4 = <Component /> //error as expected
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加