The dynamic key for an object is not being inferred by Typescript

In my Redux action, I have a simple setup:

export interface UpdateUserSettingsPayloadType {
  videoInput?: MediaDeviceInfo;
  audioInput?: MediaDeviceInfo;
  audioOutput?: MediaDeviceInfo;
}

export const updateUserSettings = (
  payload: UpdateUserSettingsPayloadType
): UserSettingsActionTypes => {
  return {
    type: UPDATE_USER_SETTINGS,
    payload,
  };
};

To correctly map the type from MediaDeviceKind to my state keys, I am using an object:

// note `type` is type MediaDeviceKind = "audioinput" | "audiooutput" | "videoinput"

const typeMap = {
 audioinput: "audioInput",
 audiooutput: "audioOutput",
 videoinput: "videoInput",
};

dispatch(
  updateUserSettings({
    [`${typeMap[type]}`]: "a string", // <- incorrect
  })
);

An error only occurs when I explicitly declare audioInput or videoInput as the key in the updateUserSettings parameter object:

dispatch(
  updateUserSettings({
    [`${typeMap[type]}`]: "I should error", // in
    audioInput: "i do error",
  })
);

Update 1

I have realized that the key is being inferred as [x: string]:

https://i.sstatic.net/ely7k.png

What I actually need is for it to be inferred as

videoInput | audioInput | audioOutput

This is the expected error I want to see:

https://i.sstatic.net/zkVo6.png

Answer №1

Alright, I'm a bit confused about what you're trying to accomplish. It seems like you want to verify the mediadevicekind by typing it, but currently, the mapped values are being interpreted as strings. To fix this, try adding "as const" after your map so that it interprets them as literal values.

edit: I think I understand your goal now:

Click here

However, why not try it this way instead: Or try this link

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

Take action once the Promise outside of the then block has been successfully completed

Presented below is the code snippet: function getPromise():Promise<any> { let p = new Promise<any>((resolve, reject) => { //some logical resolve(data); }); p.finally(()=>{ //I want do something when ou ...

Exporting ExpressJS from a TypeScript wrapper in NodeJS

I've developed a custom ExpressJS wrapper on a private npm repository and I'm looking to export both my library and ExpressJS itself. Here's an example: index.ts export { myExpress } from './my-express'; // my custom express wrap ...

Potential explanation for unexpected Typescript initialization error

I am encountering the compiler error The property 'options' is not initialized or assigned in the constructor. However, upon reviewing the code for the respective class, it is clear that this reported error does not accurately reflect the actual ...

Issue: The function "MyDocument.getInitialProps()" needs to return an object containing an "html" prop with a properly formatted HTML string

Check out my project on GitHub at https://github.com/Talita1996/NLW4 To start the project, I used the command yarn create next-app project_name I made changes to some files by modifying their extensions and adding new code Next, I added typescript to the ...

Tips for troubleshooting TypeScript integration tests within Pycharm

Currently, I have been utilizing PyCharm to code in typescript. To run tests in the integration directory, I execute npm run test:integration. However, I am now looking to debug the tests. The directory structure looks like this: my_project /src /tests ...

Whenever I try to execute 'docker build --no-cache -t chat-server .', I always encounter type errors

Below is the Dockerfile located in the root directory of my express server: FROM node:18 WORKDIR /usr/src/server COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 RUN npm run build CMD ["npm", "start"] Here is the contents of my .dockerign ...

Struggling to convert my VueJS component from JavaScript to TypeScript, feeling a bit lost

I am new to VueJS and I am facing a challenge converting my VueJS project to use TypeScript. I have been trying to bind functions to certain variables in JavaScript, but I am struggling with accomplishing the same in TypeScript. Even though there are no er ...

Issue encountered during ng2-redux installation

While attempting to use the https://www.npmjs.com/package/ng2-redux link, I encountered an issue when running npm install redux ng2-redux --save. Here is the stacktrace of the error: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files& ...

Adding a cell break line within AG-GRID in an Angular application

I'm trying to display two sets of data in a single cell with ag-grid, but I want the data to be on separate lines like this instead: Data with break line I attempted to use "\n", "\r", and "\br" but it didn't work. Here is my code ...

Combining class and data within an iteration while utilizing ngFor

I have a dynamic table with rows generated using ngFor <tbody> <tr *ngFor="let item of Details"> <div class="row details-row row-cols-lg-2 row-cols-1" *ngIf="closureDetails"> <div ...

Is it possible for a React selector to retrieve a particular data type?

As a newcomer to React and Typescript, I am currently exploring whether a selector can be configured to return a custom type. Below is a basic selector that returns a user of type Map<string, any>: selectors/user.ts import { createSelector } from ...

Getting the id of a single object in a MatTable

I'm currently working on an angular 8 application where I've implemented angular material with MatTableDatasource. My goal is to retrieve the id from the selected object in my list: 0: {id: "e38e3a37-eda5-4010-d656-08d81c0f3353", family ...

Obtain merged types by accessing a particular property within a deeply nested object

My query is reminiscent of a post on Stack Overflow titled Get all value types of a double-nested object in TypeScript However, my specific requirement involves extracting union types from the values of a designated property. const tabsEnum = { IDCardRe ...

Dynamic controller in TypeScript with React Hook Form

Is there a way to ensure that the fieldName is always inside the control? Passing a field name that doesn't exist in the form causes issues for me, so I'm looking for a solution. Can anyone help? import { Control, Controller } from 'react-ho ...

MERN stack project encountering PUT 401 Unauthorized error despite passing Bearer token

After successfully integrating the Razorpay payment gateway into my e-commerce website, I encountered an issue where a failure action was dispatched instead of a success action right after the payment process. The error message indicated that it was 401 un ...

Exploring the method to retrieve a dynamically added property in Typescript

My React Component Loader receives certain props. The contentAlign property is only available when the local property exists and its value is 'relative'. I am encountering an error when trying to include contentAlign in the props, and I cannot ...

Error TS2315: Invalid Type Assignment for Angular 6 ModuleWithProviders

Hey there, I'm encountering an issue that's got me scratching my head. I've shared some of my code in the hopes that it might shed some light on the problem. The problem cropped up as soon as I started working on a Reactive Form. Let me s ...

Avoid navigating to the subscribe block when the server sends a response in Angular

When trying to send a request to the server and check the response, I am not seeing any results. The code for sending the request is below: SendVerificationInfo(item: SendVerificationModel): Observable < any > { return this.httpClient.post < any ...

React js State not being Updated with New Values in the State Object

I'm currently learning React and hooks, and I'm facing an issue with setting the disabled state in the code snippet below. I want to disable the input field if the state.items.length is greater than 3, but I'm not seeing the updated values i ...

Is there a way to seamlessly share TypeScript types between my Node.js/Express server and Vite-React frontend during deployment?

I'm currently tackling a project that involves a Node.js/Express backend and a Vite-React frontend. My goal is to efficiently share TypeScript types between the two. How should I configure my project and build process to achieve this seamless type sha ...