When it comes to Typescript interfaces, subsequent fields are not overloaded or merged

So I've been exploring interfaces in TypeScript and their ability to merge different types, but I ran into a hiccup while transpiling my script.

Here's where things went wrong in my interface:

export interface StoreConfig extends Document, TimeStamps {
  type: 'webhook'
  metadata: {
    endpoint: string
    method: HttpMethod
    secret: string
    event: string | string[]
  }
}

export interface StoreConfig extends Document, TimeStamps {
  type: 'buylink'
  metadata: {
    prodId: string
    key: string
    expire: Date
  }
}

export interface StoreConfig extends Document, TimeStamps {
  type: 'paymentmethod'
  metadata: {
    apiKey: string
    mode: string
    whsecret: string
  }
}

Upon transpiling the TypeScript script, I received the following error:

Subsequent property declarations must have the same type.  Property 'type' must be of type '"webhook"', but here has type '"buylink"'.

On a side note, I've noticed that some libraries (like nodemailer and inquirer) load typings based on certain conditions or flags.

Answer №1

/**
 * Simple illustration
 */

export interface StoreConfig extends Document {
    type: 'webhook'

}

export interface StoreConfig extends Document {
    type: 'buylink'

}

export interface StoreConfig extends Document {
    type: 'paymentmethod'
}

/**
 * Explanation of functionality
 * 1) 
 */

export interface A {
    type: 'buylink'

}

export interface A {
    payload: number
}

type O = keyof A // type | payload

/**
 * Constraint of types
 */

type CustomType = 'buylink' & 'webhook' // never

/**
 * The above type is considered unattainable
 * Merge should be interpreted as & operator at a high level
 */

Demo1

Creating a union type is necessary. As mentioned in the comment by @ritaj:

export interface StoreConfig1 extends Document {
    type: 'webhook'

}

export interface StoreConfig2 extends Document {
    type: 'buylink'

}

export interface StoreConfig3 extends Document {
    type: 'paymentmethod'
}

type StoreConfig = StoreConfig1 | StoreConfig2 | StoreConfig3

Demo2

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

Issue with JWT Cookie not being stored in browser on Express server

Currently, my goal is to securely store a JWT in cookies within the browser for easy access when making API calls through protected routes. Displayed below is a simplified login script (without error handling) that verifies if a user's email and pass ...

When the value is empty, MUI Autocomplete will highlight all items

I have encountered a specific issue. I am working on developing a custom Autocomplete Component for filtering purposes. However, I recently came across the following Warning. MUI: The value provided to Autocomplete is invalid. None of the options matc ...

The inability to retrieve a MongoDB collection in a Node.js application through Mongoose, which was initially inserted via an AWS Lambda function employing

I attempted to insert a document using MongoClient() and then retrieve it using Mongoose, but to my disappointment, the result was an empty array. To be more specific, I performed the insertion within a Lambda function and tried fetching it inside a node ...

NextJS applications can encounter issues with Jest's inability to parse SVG images

Upon running yarn test, an unexpected token error is encountered: Jest encountered an unexpected token This typically indicates that Jest is unable to parse the file being imported, suggesting it's not standard JavaScript. By default, Jest will use ...

Is there a way to determine if a React functional component has been displayed in the code?

Currently, I am working on implementing logging to track the time it takes for a functional component in React to render. My main challenge is determining when the rendering of the component is complete and visible to the user on the front end. I believe t ...

What is the process for type checking a Date in TypeScript?

The control flow based type analysis in TypeScript 3.4.5 does not seem to be satisfied by instanceof Date === true. Even after confirming that the value is a Date, TypeScript complains that the returned value is not a Date. async function testFunction(): ...

Angular 2 destroy outlet-content and refresh the view

Is there a method in Angular 2 to remove a component that was automatically created within a router-outlet? I am looking to destroy it so that a new one is generated when I navigate back to that outlet (or is there a way to reload the outlet?). ...

What is the best way to utilize the typescript module for detecting and managing typescript errors and warnings in your code?

Currently, I am experimenting with the typescript module to programmatically detect typescript errors. Below is a simplified version of what I have been working on: var ts=require('typescript') var file_content=` interface Message{ a:string ...

The Observable merge operation encountered an error: it cannot access the 'apply' property of an undefined value

I am currently working on setting up a sorted DataTable in an angular application, and while implementing it using this example, I encountered the following error: ERROR TypeError: Cannot read property 'apply' of undefined at TableDataSource ...

What exactly does the $any() type cast in Angular do and how is it used?

While browsing the Angular.io site, I came across this title: The $any() type cast function There are instances where a binding expression may trigger a type error during AOT compilation and it is not possible or difficult to fully specify the type. To re ...

Implementing repeated logic for various data types within an Express application using Mongoose for Node.js

In the process of creating an Express REST API that interacts with a MongoDB using Mongoose, I encountered multiple data types in the database such as User, Book, Food, and more. While writing endpoints and functions for these different data types, I notic ...

An error occurred in the ngrx store with Angular during production build: TypeError - Unable to access property 'release' of undefined

After deploying my application and running it, I encountered an issue that seems to be happening only during production build at runtime. At this point, I am uncertain whether this is a bug or if there is a mistake in my code. The error "TypeError: Cannot ...

Verify in Mongo if a specific document is already present

Currently in development of my MEAN app, the client-side sends a $http POST request to my API with a JSON array containing soundcloud track data specific to each user. My goal now is to save these tracks to my app database within a 'tracks' table ...

Looking for someone to break down this Typescript code snippet for me

As a Javascript developer, I am currently diving into an unfamiliar TypeScript code block within a project. Here is the code snippet: ViewModel newPropertyAddress = new ViewModel(){name, previousPro = oldValue } ...

My reselect function seems to be malfunctioning - I'm not receiving any output. Can anyone help me

I'm looking to implement reselect in my code to retrieve the shopping cart based on product ids. Here's my reselect.ts file: import { createSelector } from "reselect"; import { RootState } from "../store"; export const shopp ...

Limit an object to only contain interface properties

Suppose we have the following object: o {a : 1, b : 2} and this interface defined as: interface MyInterface { a : number } We are now looking to create a new object that represents the "intersection" of o and the MyInterface: o2 : {a : 1} The mai ...

Tips for altering the color of the MUI table sort label icon:

Does anyone know how to change the color of the table sort label icon from gray to red? I am having trouble figuring it out. Any recommendations or suggestions would be greatly appreciated. Here is the code I have been trying to work with: <TableSortL ...

Cannot send response headers once they have already been sent to the client [NEXTJS]

Currently, I am engrossed in a personal project focused on creating a dashboard using NextJS. This project serves as an opportunity for me to delve into learning NextJS and the fundamental concepts of TypeScript. My primary challenge at the moment revolves ...

populate a data list with information sourced in Angular 8

I am looking to populate this model oldDataSource: Array<any> = []; with the values from the datasource. This is the code I have tried: ngOnInit(): void { this.dataSourceInit(); } dataSourceInit(): void { this.dataSource = new DefaultScore ...

Ionic 3 and Angular 6: Json Input Ended Abruptly

I've come across numerous discussions about the error I'm experiencing, but none of the solutions seem to apply to my situation. This morning, when I ran my code, I encountered the "Unexpected end of Json Input" error. Interestingly, I hadn' ...