TypeScript 看不到使用引用多种类型的类型定义的类型

TypeScript not seeing defined types using a type that references multiple types

我定义了一个类型,如下所示:

export type MediaProps = ImageMediaProps | OembedProps;

然后将其引用的类型定义为该代码上方的以下内容:

type SharedMediaProps = {
  /** Media type */
  type: "image" | "oembed";
  /** Media source URL */
  src: string;
};

type ImageMediaProps = SharedMediaProps & {
  /** Image alternate text */
  alt: string;
  /** Image width */
  width: number;
  /** Image height */
  height: number;
};

type OembedProps = SharedMediaProps & {
  /** Enable video autoplay */
  autoplay?: boolean;
  /** Enable video loop */
  loop?: boolean;
  /** Allow fullscreen */
  allowFullscreen?: boolean;
  /** Allow picture-in-picture */
  allowPictureInPicture?: boolean;
  /** oEmbed title */
  title?: string;
};

然后在我的 React 组件中,我有:

export function Media({
  type,
  title,
  width,
  height,
  src,
  autoplay = false,
  loop = false,
  allowFullscreen = true,
  allowPictureInPicture = true,
}: MediaProps) {

但我收到通知说 titlewidthheightautoplayloopallowFullscreenallowPictureInPicture 未定义。

例如,我收到的具体通知是:

Property 'allowFullscreen' does not exist on type 'MediaProps'.ts(2339)

它也发生在我创建的其他组件上。

我相信您需要在 MediaProps 作业中使用 intersection type

export type MediaProps = ImageMediaProps & OembedProps;

首先把type属性移到not shared props中,这样可以用来区分类型:

type SharedMediaProps = {
   /** Media source URL */
   src: string;
};

type ImageMediaProps = SharedMediaProps & {
   /** Media type */
   type: "image";
   /** Image alternate text */
   alt: string;
   /** Image width */
   width: number;
   /** Image height */
   height: number;
};

type OembedProps = SharedMediaProps & {
   /** Media type */
   type: "oembed";
   /** Enable video autoplay */
   autoplay?: boolean;
   /** Enable video loop */
   loop?: boolean;
   /** Allow fullscreen */
   allowFullscreen?: boolean;
   /** Allow picture-in-picture */
   allowPictureInPicture?: boolean;
   /** oEmbed title */
   title?: string;
};

然后将 MediaProps 定义为这些类型的联合:

type MediaProps = ImageMediaProps | OembedProps;

毕竟你仍然无法解构参数中的 属性 因为你必须先区分类型:

export function Media(props: MediaProps) {
   if(props.type === "image") {
      const {alt, width, height} = props;
   } else {
      const {autoplay, loop, allowFullscreen, allowPictureInPicture, title} = props;
   }
}

演示:https://tsplay.dev/NBkVnm