Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Generic interface and union type on nested interface

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading