TypeScript至少需要*一个属性

TypeScript至少需要*一个属性,typescript,typescript-typings,Typescript,Typescript Typings,假设我有一个接口 export interface IAlert { cta?: CTA; description?: string; title?: string; } 您将如何键入该属性,以便至少传入一个属性,同时也允许传入所有三个属性 我试过 export type TAlert = { type?: EAlertType; } & ( | { cta: CTA; description?: st

假设我有一个接口

    export interface IAlert {
      cta?: CTA;
      description?: string;
      title?: string;
    }
您将如何键入该属性,以便至少传入一个属性,同时也允许传入所有三个属性

我试过

export type TAlert = {
  type?: EAlertType;
} & (
  | {
      cta: CTA;
      description?: string;
      title?: string;
    }
  | {
      cta?: CTA;
      description: string;
      title?: string;
    }
  | {
      cta?: CTA;
      description?: string;
      title: string;
    }
);
但是,我对它显示的错误消息不满意

Type '{}' is not assignable to type 'IntrinsicAttributes & TAlert'.
  Property 'title' is missing in type '{}' but required in type '{ cta?: any; description?: string; title: string; }'

我不确定如何维护接口的使用并要求至少传入一个属性,或使用
类型,但提供一个更有意义的错误。

我无法帮助处理错误消息,但您可以简化:

export type TAlert = {
    type?: EAlertType;
    cta?: CTA;
    description?: string;
    title?: string;
  } & (
    | {
        cta: CTA;
      }
    | {
        description: string;
      }
    | {
        title: string;
      }
);

您可以使用类而不是接口在构造函数中进行验证