Typescript:如果设置了另一个可选类型,则需要设置类型

Sir*_*hau 3 typescript

如果设置了第一种类型(本身是可选的),我想需要第二种类型。 有时我在代码中遇到问题,即设置一个可选属性后,还需要提供其他属性才能使反应组件正常工作。

例子

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
}
Run Code Online (Sandbox Code Playgroud)

原因是通过类型检查强制组件行为一致。所有放大的组件都应包含文本和图像。

有没有办法通过 TypeScript 辅助函数或逻辑来实现这一点?

Tit*_*mir 8

您可以使用受歧视的联合:

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
Run Code Online (Sandbox Code Playgroud)

游乐场链接