Home > Enterprise >  Generic interface and union type on nested interface
Generic interface and union type on nested interface

Time:01-12

I want to create a type that allows me to define a prop (for a react component):

type RV<T> = {
    base: T;
    tablet?: T;
    desktop?: T;
};

export type ResponsiveValue<T> = RV<T> | T;

This works fine for strings, numbers and booleans, meaning I can use

backgroundUrl: ResponsiveValue<string>

And I can pass in backgroundUrl either as string or as the interface (where the values are string). All cool.

If I do the same with an interface, instead

type StaticImageData = {
    src: string;
    height: number;
    width: number;
    blurDataURL?: string;
};

export type ImageProps = {
  imageData: ResponsiveValue<StaticImageData>;
};

And I try to if (imageData.base) I get the good old typescript error:

Property 'base' does not exist on type 'ResponsiveValue<StaticImageData>'.   Property 'base' does not exist on type 'StaticImageData'

How can I fix the ResponsiveValue type definition to make it work with interfaces as well?

CodePudding user response:

You just need to change the type of typguard you are using to be an in type guard:

declare const imageData: ResponsiveValue<StaticImageData>;

if ('base' in imageData) {
    imageData.base
}

Playground Link

  •  Tags:  
  • Related