最初のタイプ(それ自体はオプション)が設定されている場合、2番目のタイプが必要です。コードに問題がある場合があります。1つのオプションのプロパティを設定すると、reactコンポーネントが機能するために他のプロパティも指定する必要があります。
例
interface ComponentProps {
title: string;
isEnlarged?: boolean;
text?: string; // <-- If isEnlarged is set, text shouldn't be optional
imageUri?: string // <--- If isEnlarged is set, imageUri shouldn't be optional
}
その理由は、タイプチェックを通じて一貫したコンポーネントの動作を強制するためです。拡大されたすべてのコンポーネントには、テキストと画像の両方が必要です。
TypeScriptヘルパー関数またはロジックによってそれを達成する方法はありますか?
識別された共用体を使用できます。
type ComponentProps = {
title: string;
} & ({
isEnlarged: true; // asuming this must be true for otehrs to be required
text: string;
imageUri: string
} | {
isEnlarged?: false; // asuming this must be true for otehrs to be required
text?: string;
imageUri?: string
})
let a: ComponentProps = { title: "test" } //ok
let b: ComponentProps = { title: "test", isEnlarged: true } //err
let c: ComponentProps = { title: "test", isEnlarged: true, imageUri: "", text: "" } //ok
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加