What's the most efficient way to define the type of an object in TypeScript when one of its properties shares the same name as the type itself?

I'm currently working on processing an event payload where the event field is a string, and the content of data depends on the value of the event field. While I have come up with a representation that functions correctly, I can't help but feel that there might be a better or more conventional approach:

type EventMap = {
  created: { created: string },
  updated: { updated: string }
}

type Payload<T extends keyof EventMap> = {
  event_id: string;
  event: T;
  data: EventMap[T];
};

type Payloads = Payload<'created'> | Payload<'updated'>

It seems redundant to keep mentioning created and updated. However, using Payload<keyof EventMap> doesn't quite fit either as it allows for any combination.

Answer №1

You can achieve something similar by doing the following:

type Payloads = { [K in keyof EventMap]: Payload<K> }[keyof EventMap]

Playground

Alternatively, you can directly create the Payloads type from the EventMap:

type Payloads = {
    [K in keyof EventMap]: {
        event_id: string;
        event: K;
        data: EventMap[K];
    }
}[keyof EventMap]

Playground


// works
const x: Payloads = {
    event_id: 'x',
    event: 'created',
    data: {
        created: 's'
    }
}

// works
const y: Payloads = {
    event_id: 'x',
    event: 'updated',
    data: {
        updated: 's'
    }
}

// error due to mixed updated and created
const z: Payloads = {
    event_id: 'x',
    event: 'updated',
    data: {
        created: 's'
    }
}

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 error message ``TypeError [ERR_UNKNOWN_FILE_EXTENSION]:`` indicates a

I am encountering an error while trying to run the command ./bitgo-express --port 3080 --env test --bind localhost: (node:367854) ExperimentalWarning: The ESM module loader is experimental. internal/process/esm_loader.js:90 internalBinding('errors ...

Encountering difficulty in retrieving the outcome of the initial HTTP request while utilizing the switchMap function in RxJS

My goal is to make 2 HTTP requests where the first call creates a record and then based on its result, I want to decide whether or not to execute the second call that updates another data. However, despite being able to handle errors in the catchError bl ...

Remove the package from the @types folder within the node_modules directory

I currently have the 'mime' library in my node_modules directory and I am looking to completely remove it from my project, along with its @types files. The reason for this is that the old mime package is not functioning correctly for me, so I wan ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

Encountering CORS error when making a call to AWS API from Angular 9

Currently, I am working on implementing a post method in Angular 9 that interacts with an AWS API. However, upon calling the post function in Angular 9: this.http.post(url, body, requestOptions), I encountered an error in my browser stating: Access to XMLH ...

Updating a label dynamically in Angular

QUESTION: Is there a way to dynamically change the text of a label based on a certain condition? Specifically, I want the label to be blank when I'm on a specific route in my App. CURRENT APPROACH: <RadSideDrawer allowEdgeSwipe=&quo ...

Is it feasible to customize Angular Material Constants within select.ts?

I am looking for a way to dynamically set the height of a select element by passing a variable, but the height is currently a constant in the material code (select.ts). Check out the mat-select documentation View the source code on Github: material2 / se ...

What makes Mathematics a unique object in JavaScript programming?

Recently, I've dived into learning Javascript, so pardon me if my doubts seem a bit illogical. I came across the definition for a Math object, and here is the code snippet: interface Math { /** The mathematical constant e. This is Euler's nu ...

Ensure Jest returns the accurate file paths for images in a TypeScript and React environment

I'm currently developing a React application and I have come across an issue with importing images. My usual method of importing images is as follows: import image1Src from 'assets/img1.png"; For testing purposes, I need to be able to make ...

Error: XYZ has already been declared in a higher scope in Typescript setInterval

I've come across an interesting issue where I'm creating a handler function and trying to set the current ref to the state's value plus 1: const useTimer = () => { const [seconds, setSeconds] = useState(0); const counterRef = useRef(n ...

Create a global variable by importing an external module in TypeScript

I am currently developing a TypeScript npm module called https://www.npmjs.com/package/html2commonmark. This module is versatile and can be utilized in nodejs (via require) as well as in the browser (by loading node_modules/html2commonmark/dist/client/bund ...

I encountered a problem when trying to set up ngx-Spinner version 8.0.3

I need help implementing a spinner loader in my app. I have followed the instructions provided at [ https://www.npmjs.com/package/ngx-spinner ] and successfully installed it. However, when trying to import and add it to "imports", I encountered the follow ...

NestJS does not recognize TypeORM .env configuration in production build

Currently, I am developing a NestJS application that interacts with a postgres database using TypeORM. During the development phase (npm run start:debug), everything functions perfectly. However, when I proceed to build the application with npm run build a ...

React | What could be preventing the defaultValue of the input from updating?

I am working with a stateful component that makes a CEP promise to fetch data from post offices. This data is retrieved when the Zip input contains 9 characters - 8 numbers and a '-' - and returns an object with the desired information. Below is ...

Determining the height of dynamically rendered child elements in a React application

Looking for a way to dynamically adjust the heights of elements based on other element heights? Struggling with getting references to the "source" objects without ending up in an infinite loop? Here's what I've attempted so far. TimelineData cons ...

The return type in Typescript is populated with a generic type name that lacks meaningful

When utilizing ts-results-es, I encounter an issue. This library aids in wrapping errors within a class to provide insight into potential function errors. Here is a simplified class definition: interface BaseResult<T, E> {} class Err<E> imple ...

What is the solution for resolving the no-unsafe-any rule?

Currently incorporating TSLint for maintaining the quality of my Angular TypeScript code. I've opted to activate the 'no-unsafe-any' rule from TSLint, as it appears beneficial to avoid making assumptions about properties with type 'any& ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Utilizing asynchronous methods within setup() in @vue-composition

<script lang="ts"> import { createComponent } from "@vue/composition-api"; import { SplashPage } from "../../lib/vue-viewmodels"; export default createComponent({ async setup(props, context) { await SplashPage.init(2000, context.root.$router, ...

Encountering error "module fibers/future not found" while creating a meteor method in typescript

While working on a Meteor method for async function in my project that combines Meteor with Angular2 using Typescript ES6, I encountered an error. The issue is related to a sync problem in the insert query when inserting data with the same name. To resolve ...