Utilizing string literals as index signatures

I've created a code snippet called MyTest that maps over an object:

type MyTest<T> = {
  [P in keyof T]: T[P];
};

type Result = MyTest<{hello: 'world', foo: 2}>;
//   ^? type Result = { hello: 'world', foo: 2 }  👍

But when I input a string literal like hello, I just get hello back. I'm curious as to why this happens.

type Result2 = MyTest<"hello">;
//   ^? type Result2 = "hello"  👀

I have two theories about what could be causing this:

  1. The iteration may involve keys such as toString(), resulting in an object with approximately 35 keys all assigned the value of never.
  2. Or perhaps the iteration doesn't occur because there's nothing to iterate on. In that case, what would the default value be?

Answer №1

This topic was recently discussed on this GitHub thread. When using mapped types to iterate over primitives, the result will just be the primitive itself.

When declaring mapped types as { [ K in keyof T ]: U } where T is a type parameter, they are referred to as homomorphic mapped types. This means that the mapped type preserves the structure of T. If the type parameter T is a primitive type, the mapped type will simply evaluate to the same primitive.

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

No data found in the subrow of the datasource after the filter has been

I am working with a material table that has expandable rows. Inside these expanded rows, there is another table with the same columns as the main table. Additionally, I have implemented filters in a form so that when the filter values change, I can update ...

Guide to importing a markdown document into Next.js

Trying to showcase pure markdown on my NextJS Typescript page has been a challenge. I attempted the following: import React, { useState, useEffect } from "react"; import markdown from "./assets/1.md"; const Post1 = () => { return ...

Dynamically loading classes in TypeScript without using default export

Is there a way to dynamically load classes in TypeScript without using a default export method? I have managed to make it work partly, but I am looking for a solution that doesn't require a default export: export default class Test extends Base { ... ...

Error message: An unhandled TypeError occurs when attempting to access properties of an undefined object (specifically, the 'then' property) while refreshing the token using axios

Is there a way to refresh tokens in axios without interrupting the flow? For example, when the server returns an access token expiration error, I want to queue the request and replay it after getting a new token. In React, I'm using promises as shown ...

What techniques can I use to modify an object while it's being iterated through?

I've been attempting to manipulate the object while looping through it, but unfortunately, it's not working. How can I modify it so that the constant patient includes the property lastActivity inside the this.model array? My code looks like this ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...

TypeScript: Defining a custom type based on values within a nested object

I'm attempting to generate a unique type from the value of a nested object, but encountering failure if the key is not present on any level of nesting. Can someone point out where I might be making a mistake? const events = [ { name: 'foo&apos ...

Is there a way to locate a prior version of the NPM @types package?

Currently, I am utilizing Angular version 1.4.7 and in need of a type file corresponding to this specific version. Browsing through the NPM website, I came across a type file for AngularJs listed as version 1.5.14 alpha. Is there a way to access a compreh ...

The specified instant cannot be located in 'moment' while attempting to import {Moment} from 'moment' module

Struggling in a reactJS project with typescript to bring in moment alongside the type Moment Attempted using import moment, { Moment } from 'moment' This approach triggers ESLint warnings: ESLint: Moment not found in 'moment'(import/n ...

Inoperative due to disability

Issue with Disabling Inputs: [disabled] = true [disabled] = "isDisabled" -----ts > ( isDisabled=true) Standard HTML disabler disable also not functioning properly [attr.disabled] = true [attr.disabled] = "isDisabled" -----ts > ( isDisabled=true) ...

It is feasible to completely override a class in TypeScript

I have a subclass defined as follows: customException.ts /** * Custom Error class. * * @class Error * @extends {Error} */ class Error { /** * @type {string} * @memberof Error */ message: string; /** * @type {boolean} * @memberof ...

Can the inclusion of additional parameters compromise the type safety in TypeScript?

For demonstration purposes, let's consider this example: (playground) type F0 = (x?: string) => void type F1 = () => void type F2 = (x: number) => void const f0: F0 = (x) => console.log(x, typeof(x)) const f1: F1 = f0 const f2: F2 = f1 f ...

Testing Angular components that have protected @Input properties

Typically, we designate variables as protected when they are only used within a component and its subclasses, but not in the template itself. This approach becomes particularly advantageous when a class contains multiple variables, as it makes it easy to ...

Angular : Is toFixed() functioning properly with one value but not with the other one?

My form has 2 inputs, each calling the calculeSalaire() function. calculeSalaire() { this.fraisGestion = this.getFraisGestion(); this.tauxFraisGestion = this.getTauxFraisGestion(); this.salaireBrut = this.getSalaireBrut(); this.salaireNet = this.g ...

"Why is it that the onChange method of the antd table does not return an array of numbers for selectedRowKeys

In my current project, I am working on a Nextjs application that utilizes typescript and antd. The application includes a table component from antd which allows users to select rows. const rowSelection = { onChange: (selectedKeys: any[], selectedRows: M ...

Viewing an image from a local file on a web browser

I am currently working on a project where I want the user to be able to select a local image that will then be displayed on the page. As someone who is new to web development, I did a lot of research and found some helpful information on StackOverflow. I t ...

Dealing with the issue of incompatible types in TypeScript with Vue 3 and Vuetify: How to handle numbers that are not assignable to type Readonly<any

Currently, I am utilizing Vite 3 along with Vue 3 and Vuetify 3 (including the Volar extension and ESLint). Additionally, I am incorporating the composition API in script setup mode. Within my HTML code, I am utilizing Vuetify's v-select. Unfortunate ...

Automatic type inference for functions in TypeScript with arguments

I am looking to define an interface with the following structure: interface CheckNActSetup<D, C> { defs: (event: Event) => D, context: (defs: D) => C; exec: (context: C) => any[]; when: ((context: C) => boolean)[]; } and implement it usi ...

Converting language into class components using ngx-translate in Angular

Seeking to convert the information from a table into my typescript class. The data in the table is sourced from a JSON file within the /assets directory. Is there a method to accomplish this task? How can I categorize translation within a typescript class ...

Can you specify the necessary import statement for CallableContext?

My Google Cloud function is simple and looks like this: import * as functions from 'firebase-functions'; var util = require('util') export const repeat = functions.https.onCall( function (data, context) { console.log(&apo ...