What is the best way to create an interface with multiple property types in TypeScript?

Is it possible to create an interface property in TypeScript that can hold two different interfaces?

interface IPayload1 {
  id: string;
  name: string;
}
interface IPayload2 {
  id: string;
  price: number;
}

interface Demo {
  // Can we achieve this?
  payload: IPayload1 | IPayload2;
}

Answer №1

It is worth mentioning that your code is functional, as properties can be defined to accept a range of types by utilizing the | operator, known as a Union Type.

When dealing with union types, it may be necessary to implement type guards or casts in situations where you need to access properties that are specific to only certain types within the list. For instance:

const demo: Demo = {
  payload: {
    id: '1',
    name: 'boo',
  },
};

const demo2: Demo = {
  payload: {
    id: '1',
    price: 25,
  },
};

// Property is common to all types
demo.payload.id;

// Without explicit casting, accessing these properties will result in errors
(demo.payload as IPayload1).name;
(demo.payload as IPayload2).price;

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

Due to a TypeScript error stating that the type '{ Id: number; Name: string; }' cannot be utilized as an index type, I am unable to assign a value for students at this time

I am facing an issue with defining a value for students in TypeScript. It is giving me an error saying that it can't be used as index type. Just to clarify, I have declared id as number (not Number) and Name as string (not String). import { Component ...

Exploring the TypeScript handbook: Utilizing rootDirs for Virtual Directories

Exploring the concept of Virtual Directories with rootDirs in the handbook, we find an interesting example demonstrating how modules can be imported from different source folders by combining multiple rootDirs. // File Structure src └── views ...

I'm curious about the origins of the "readme" field within the artifact registry file

Within our private npm registry on Azure, we house our own npm package alongside the npmjs packages. One particular package, @typescript-eslint/parser, has caused our pipelines to fail during the npm install task due to a SyntaxError: Unexpected end of JSO ...

Having trouble with implementing custom checkboxes in a d3 legend?

My attempt at creating checkboxes in d3 has hit a snag. Upon mouse click, the intention is for them to be filled with an "x". Strangely, using d3.select() inside the click-function doesn't seem to work as expected, although adding the letter U for the ...

The struggle of accessing child components using ViewChild in Angular

I am facing an issue with a dialog box that is supposed to display a child component separately. Below is the code for the child component: @Component({ selector: 'userEdit', templateUrl: './edituser.component.html', styleUrls: [ ...

Custom "set attribute" feature in TypeScript

One issue I faced was resolved by creating the function shown below : function setProperty<T extends Record<string, string>>(obj: T, key: keyof T) { obj[key] = "hello"; } However, when I tried to compile the code, I encountered an ...

Ways to implement distinct values for model and input field in Angular 5

I'm currently working on an Angular 5 application and I have a requirement to format an input field with thousand separators (spaces). However, the model I am using only allows numbers without spaces. Since my application is already fully developed, ...

Creating a shared singleton instance in Typescript that can be accessed by multiple modules

Within my typescript application, there is a Database class set up as a singleton to ensure only one instance exists: export default class Database { private static instance: Database; //Actual class logic removed public static getInstance() ...

TS2322: Subclass missing property, yet it still exists

In my project, I have defined two Angular 4 component classes. The first class, referred to as the superclass: export class SectionComponent implements OnInit { slides: SlideComponent[]; constructor() { } ngOnInit() { } } And then there&apo ...

Having trouble updating state with useEffect in a React functional component

Currently, I am dealing with a React functional component that is calling an API to fetch data. The response from the API call is confirmed to be received successfully. My aim is to store this data in an array within the component's state so that it c ...

AngluarFire 2 authState function displaying null after refreshing the page

Currently, I am working on integrating Firebase with AngularFire 2 and facing an issue. The problem arises when I try to refresh the page, as the auth instance returns null. Below is the code snippet for my AuthService: Everything functions correctly, b ...

Typescript UniqueForProp tool not working as expected

I've created a utility function called UniqueForProp that takes an array of objects and a specified property within the object. It then generates a union type containing all possible values for that property across the array: type Get<T, K> = K ...

executing afterEach in multiple specification files

Seeking a solution to execute shared code across tests in various spec files in Playwright using TypeScript. Specifically, I need to upload test results based on the testInfo. While I know that fixtures can achieve this, it's not the most efficient op ...

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Discover how to access JSON data using a string key in Angular 2

Trying to loop through JSON data in angular2 can be straightforward when the data is structured like this: {fileName: "XYZ"} You can simply use let data of datas to iterate over it. But things get tricky when your JSON data keys are in string format, li ...

Navigating through JSON object using Angular 2's ngFor iterator

I want to test the front end with some dummy JSON before I write a service to get real JSON data. What is the correct way to iterate through JSON using ngFor? In my component.ts file (ngOnInit()), I tried the following code with a simple interface: var js ...

Transitioning from ng-repeat filter to Typescript

As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature. Initially, my HTML template looked like t ...

Typescript compilation fails to include require statements in certain files

Currently, I am in the process of converting a Node.js project to TypeScript. The first two main files of the Node project transpiled correctly, but the third file ran into issues with the requires statement at the top for pulling in dependencies. Despite ...

Break down and extract elements using typedEvent in TypeScript

Within the external library, there is the following structure: export interface Event extends Log { args?: Result; } export interface TypedEvent<EventArgs extends Result> extends Event { args: EventArgs; } export type InstallationPreparedEven ...

finding the adjacent li element using the document.(property)

Utilizing a pub/sub solution named ably.io for real-time data updates, I have implemented a method that assigns dynamic ids to each ngFor listing. This allows me to easily identify and update the values received from ably.io subscribe. document.getElement ...