Implementation of a nested interface using a generic and union types

I am seeking to create a custom type that will enable me to specify a property for a react component:

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

export type ResponsiveCustomValue<T> = CustomType<T> | T;

This setup functions well with strings, numbers, and booleans, allowing me to use

backgroundUrl: ResponsiveCustomValue<string>

I can easily provide backgroundUrl either as a string or within the interface structure (containing string values). Everything works smoothly.

However, if I attempt to apply the same logic with an interface, like so

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

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

And then try to check if (imageData.base), I encounter the familiar typescript error:

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

Is there a way to adjust the definition of the ResponsiveCustomValue type to properly work with interfaces?

Answer №1

To implement the code modification, simply switch the typguard type to an in type guard:

declare const imageData: ResponsiveValue<StaticImageData>;

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

Access Playground Link Here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The typescript MenuProvider for react-native-popup-menu offers a range of IntrinsicAttributes

Looking to implement drop-down options within a Flatlist component, I've utilized the React Native Popup Menu and declared MenuProvider as the entry point in App.tsx. Encountering the following error: Error: Type '{ children: Element[]; }' ...

The data type 'string | undefined' cannot be assigned to the data type 'string' when working with .env variables

Trying to integrate next-auth into my nextjs-13 application, I encountered an error when attempting to use .env variables in the [...nextauth]/route.ts: Type 'string | undefined' is not assignable to type 'string'. https://i.stack.im ...

I am trying to figure out how to send a One Signal notification from my Ionic app using the One Signal REST API. I have reviewed the documentation, but I am still unable to understand it

Is there a way to send a one signal notification from my ionic app using the one signal API? I have reviewed the documentation but am having trouble with it. While I have set up the service and it is functional, I can only manually send notifications thr ...

Creating a TypeScript function that can dynamically assign values to a range of cells within a column, such as AD1, AD2, AD3, and so on

Hello there I'm currently working on a function that will dynamically assign values to the column range of AE to "AD" + i. However, when I use the function provided below, it only writes AD5 into the first 5 columns instead of AD1, AD2, AD3, and so o ...

Why does `react/require-default-props` still display an error even when a default prop value has been set?

This inquiry pertains to the guideline require-default-props. Here is the code snippet in question: function MyComponent({ blubb = 'my default', }: { blubb?: string, }) { // blubb defaults to 'my default' }; Eslint is flagging a ...

Ionic 2: Unveiling the Flipclock Component

Can anyone provide guidance on integrating the Flipclock 24-hours feature into my Ionic 2 application? I'm unsure about the compatibility of the JavaScript library with Ionic 2 in typescript. I have searched for information on using Flipclock in Ionic ...

The attribute 'commentText' is not found within the 'Comment' data type

Currently, I am immersed in building a user-friendly social network application using Angular 12 for my personal educational journey. Running into an error has left me puzzled and looking for assistance. About the Application: The home page (home.compone ...

Tips for hiding a sidebar by clicking away from it in JavaScript

My angular application for small devices has a working sidebar toggling feature, but I want the sidebar to close or hide when clicking anywhere on the page (i.e body). .component.html <nav class="sidebar sidebar-offcanvas active" id="sid ...

Error: Interface declaration for _.split is missing in the Lodash.d.ts file

For my current typescript project that heavily relies on Lodash with lodash.d.ts, I've encountered an issue with the _.split function not being implemented yet. It's listed under the 'Later' section in the .ts file. I need to find a wo ...

Angular project service file experiencing issues with TypeScript string interpolation functionality

Here is the code snippet for a service in an Angular project: @Injectable() export class FetchDataService { fetch(link){ console.log('This is a ${link}'); } } In my component, I am invoking this method with a string parameter. Upon che ...

Navigating through nested JSON Objects for dropdown functionality in Angular 6 - a step-by-step guide

Currently, I am facing a challenge in Angular 6.0 where I am trying to use HttpClient to iterate through JSON data retrieved from a local file within my assets folder. Below is the sample JSON Data: [{ "configKey": [{ "user1": [{ ...

Using Typescript and React to manage controlled components and selecting a single checkbox within a group

all. I am currently working on a controlled component in Storybook using React and Typescript. When my Checkbox is uncontrolled, it works perfectly fine. However, I am facing some challenges with the logic and thought process when transitioning it to a ...

Exploring Child Types in Typescript and JSX minus the React framework

It seems like there's a missing piece of the puzzle that I can't quite figure out. Despite going through the documentation on JSX in non-React settings, I'm still unable to spot my mistake. Let's examine the following code: /** @jsx pra ...

Struggling to get the bindings to work in my Angular 2 single-page application template project

I have recently started using the latest SPA template within Visual Studio 2017: https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp.net-core-with-javascriptservices/ The template project is functioning properly. ...

The term 'MapEditServiceConfig' is being incorrectly utilized as a value in this context, even though it is meant to refer to a type

Why am I receiving an error for MapEditServiceConfig, where it refers to a type? Also, what does MapEditServiceConfig {} represent as an interface, and what is the significance of these brackets? export interface MapEditServiceConfig extends AppCredenti ...

Exploring the world of mouse events in Typescript using JQuery, all the while maintaining strict typing regulations

I'm currently working on a project that involves using JQuery in Typescript. One challenge I'm facing is passing a mouse event from a JQuery element to a wrapper class. Here's an example of what I'm trying to achieve: import * as $ fro ...

Angular 2: Issue with data table not updating after item deletion

I need assistance with updating a data table after deleting an item. The database is updated correctly when I delete an item, but the table does not automatically refresh to reflect the changes. managenews.component.ts import { Component, OnInit } from ...

What is the best method to add data to a child array located within a nested array?

Struggling to create an array that will display data in the following format: Healthcare -- Insights driven by data for improved healthcare -- Urban Analytics Transport -- Urban Analytics Cities -- Urban Analytics I have attempted ...

Refine the observable data

Trying to filter a list of items from my Firebase database based on location.liked === true has been a challenge for me. I've attempted using the traditional filter array method but have not had success. Can anyone suggest an alternative method to acc ...

"Learn the process of extracting information from a database and exporting it to a CSV file with Angular 2

Currently, I am facing an issue where I need to retrieve data from a database and export it to a CSV file. While I am able to fetch all the data successfully, I am encountering difficulty when trying to fetch data that is in object format as it shows up as ...