我定義了一個看起來像這樣的型別:
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) {
但我收到通知說title, width, height, autoplay, loop, allowFullscreen,allowPictureInPicture未定義。
例如,我收到的具體通知是:
型別“MediaProps”.ts(2339) 上不存在屬性“allowFullscreen”
它也發生在我創建的其他組件上。
uj5u.com熱心網友回復:
首先,將type屬性移到非共享屬性中,這樣就可以用來區分型別了:
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
uj5u.com熱心網友回復:
我相信您需要在您的 MediaProps 分配中使用交集型別。
export type MediaProps = ImageMediaProps & OembedProps;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/459152.html
標籤:javascript 反应 打字稿 反应打字稿
