The assigned value of the computed property name does not match the specified type in Record

Whenever I attempt to set a value for a Record utilizing a computed property name, a type error is thrown:

function Test<N extends string, M extends {}>(name: N, model: M) {
  const record: Record<N, M> = { [name]: model };
}
The error message states that 'Type '{ [x: string]: M; }' cannot be assigned to type 'Record<N, M>'.ts(2322)

I am puzzled as to why the right hand side of the assignment has the type { [x: string]: M; } instead of { [x: N]: M }?

Answer №1

There is a persistent issue known as a bug that has been around for quite some time, which you can find more information about in microsoft/TypeScript#13948. The problem lies in the fact that the computed property key type is incorrectly widened to string. It is uncertain whether this will be resolved soon or at all. As a temporary solution, it is recommended to use a type assertion to inform the compiler that you are aware of what you are doing:

function Test<N extends string, M extends {}>(name: N, model: M) {
    const record = { [name]: model } as Record<N, M>;
    return record; // to show something soon
}
const works = Test("okay", "hmm");
// const works: {okay: string}

It should be noted that technically, this approach may not be entirely safe when name is not solely a single string literal type. For instance, if it is a union of string literals, there is a risk of having more keys than expected at runtime:

const coin = Math.random() < 0.5 ? "heads" : "tails";
const oops = Test(coin, "hmm");
console.log(oops.heads.toUpperCase() + oops.tails.toUpperCase()); // no compile error
// TypeError at runtime!

If you do not intend to pass unconventional input for name, then this should work fine. However, if you anticipate such scenarios, you might need to take extra precautions to ensure the accuracy of the type of record:

function TestSafer<N extends string, M extends {}>(name: N, model: M) {
    const record = { [name]: model } as
        string extends N ? { [k: string]: M | undefined } :
        N extends any ? { [K in N]: M } : never;
    return record;
}

This implementation behaves as follows:

const fine = TestSafer("okay", "hmm");
// const fine: {okay: string}
const better = TestSafer(coin, "hmm");
// const better: {heads: string} | {tails: string}
const alsoBetter = TestSafer(coin + "!!", "hmm")
// const alsoBetter: { [k: string]: string | undefined; }

This represents the most cautious approach I can think of for users of Test, although the behind-the-scenes implementation involves a complex mix of assertions and conditional types.


Access code 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

Utilize string values as identifiers in type declarations

My Props type declaration currently looks like this: type Props<FormData> = { formData: FormData, sectionNme: keyof FormData, name: string } However, I am trying to modify it to look more like the following: type Props<FormData> = ...

The error message stating that property 'catch' does not exist on type 'Observable<IEmployee[]>' cannot be fixed by simply adding the import 'rxjs/add/operator/catch'

When I hover over .catch(this.errorHandler), an error message is displayed Property 'catch' does not exist on type 'Observable'.ts(2339) I am unable to import the catch function into Angular Typescript. Upon hovering over .catch(th ...

Is it possible to define a constant enum within a TypeScript class?

I am looking for a way to statically set an enum on my TypeScript class and be able to reference it both internally and externally by exporting the class. As I am new to TypeScript, I am unsure of the correct syntax for this. Below is some pseudo-code (whi ...

Is it considered valid in JavaScript or TypeScript to group values using (value1 || value2) for comparisons, and if it is, what is the reasoning behind

Does anyone know if using the || operator to group values while comparing a single variable is valid in the most recent versions of JavaScript or TypeScript? If not, what could be preventing this from becoming a valid syntactic sugar feature at some point? ...

typescript set parameter conditionally within a function

For my upcoming app, I am working on an API that will utilize Firebase FCM Admin to send messages. Below is the code snippet: import type { NextApiRequest, NextApiResponse } from "next"; import { getMessaging } from "firebase-admin/messaging ...

Potential absence of the object has been detected after performing object verification

I encountered an issue with the following error message: Object is possibly 'undefined'.ts(2532) This is what my configuration looks like: export interface IDataColumns { name: string; label: string; display: string; empty: boolean; fi ...

The ES6 import feature conceals the TypeScript definition file

I currently have two definition files, foo.d.ts and bar.d.ts. // foo.d.ts interface IBaseInterface { // included stuff } // bar.d.ts interface IDerivedInterface extends IBaseInterface { // more additional stuff } Initially, everything was funct ...

JavaScript: Manipulating Data with Dual Arrays of Objects

//Original Data export const data1 = [ { addKey: '11', address: '12', value: 0 }, { addKey: '11', address: '12', value: 0 }, { addKey: '12', address: '11', value: 0 }, { addKey: &a ...

Error: ObjectId casting unsuccessful for the input value "{ userId: '5c48a95df9bd9a33c0ff9405'"

'An issue occurred while attempting to convert the value "{ userId: '5c48a95df9bd9a33c0ff9405', username: 'ahsan', iat: 1549024353, exp: 1549110753 }" to an ObjectId for the "user" path in the "Rental" model' router.get ...

Encountered 'DatePickerProps<unknown>' error while attempting to develop a custom component using Material-UI and react-hook-form

Currently, I'm attempting to create a reusable component using MUI Datepicker and React Hook Form However, the parent component is throwing an error Type '{ control: Control<FieldValues, object>; name: string; }' is missing the follow ...

What is causing styled-components to include my attributes in the DOM?

In various parts of my code, there is a snippet like this: import React from 'react' import styled from 'styled-components' type PropsType = { direction?: 'horizontal' | 'vertical' flex?: number | string width ...

Ways to execute functions in a sequence in Angular 2/4 with Typescript

I'm struggling with running functions sequentially in my Angular 2/4 project. I have a retrieveData() function that fetches data from a service and stores it in an array. Then, there's a displayData() function that uses this data to create a char ...

Error Message: "ESLint Error: Unable to access tsconfig.json file within WebStorm IDE on WSL2 environment"

Encountering an ESLint error when cloning my repository and running npm install on WSL2. The IDE shows this error for all .ts files: ESLint: Parsing error: Unable to read file \\wsl$\ubuntu-20.04\home\project_directory\tscon ...

`Error encountered with Dynamic Imports within a React Native TypeScript component`

I am facing an issue related to dynamic imports within a React Native app that is being developed using TypeScript. My goal is to dynamically import JSON files based on a specific reference prop present in one of the components. However, I am encountering ...

Transforming a plain text field into an input field upon clicking a button or icon using Angular/Typescript

I am a beginner with Angular 6 and I'm trying to implement functionality where clicking a button or icon will change a text field into an input field. See the snippet of code and expected output below. Thank you in advance. <div> <mat-for ...

The cloud function that is callable is currently inactive and encountering errors upon invocation

I am experiencing issues with my Cloud Function which is supposed to call a request to the URL passed to it. This is my first time using TypeScript to make a request, so I added some print calls to troubleshoot the problem. However, the first log never app ...

Encountered an issue when utilizing the useRef hook in Next.js version 13

I am currently exploring nextjs13 and typescript. I encountered an issue when attempting to use the useRef hook. Below is the code snippet in question: import { useEffect, useRef } from "react" export const useDraw = () => { const canvas ...

Error: React-Redux Provider is being called incorrectly

I am currently working on a small application to get familiar with using Redux Toolkit. My understanding of React/Redux mainly comes from an outdated Udacity course. Although the error message lists the top 3 reasons for this particular error, none of the ...

Reactjs may have an undefined value for Object

I have already searched for the solution to this question on stackoverflow, but I am still confused. I tried using the same answer they provided but I am still getting an error. Can someone please help me resolve this issue? Thank you. const typeValue = [ ...

Command to update a document in AWS DynamoDB using the Document Client

While attempting to utilize the UpdateCommand feature within the AWS DynamoDB documentation, I encountered various challenges due to its lack of detailed explanation and difficulty in implementation. My aim was to employ the update command to seamlessly t ...