Can you explain the distinction between using keyof within an indexer versus outside of it?

Consider the TypeScript snippet below:

type ForwardVal<T> = { 
    [K in keyof T]: string; 
};
type ForwardKeyOf<T extends string | number | symbol> = { 
    [K in T]: string; 
};

type ByObj   = ForwardVal<number[]>;         // string[]
type ByKeyOf = ForwardKeyOf<keyof number[]>; // { length: string, toString: string, ... }

type foo =   ByObj['push'];   // (...items: string[]) => number
type bar = ByKeyOf['push'];   // string

What causes foo to be a function and not a string, while bar is indeed a string? What distinguishes forwarding a keyof obj from using Key in T when forwarding obj itself and employing Key in keyof T within a mapped type? Doesn't the T parameter simply get swapped out for its assigned value?

Answer №1

Generally speaking, there is no distinction; keyof simply represents a union type of all the keys (both properties and method names) present in the specified argument for keyof.

However, TypeScript 3.1 introduced a special case where the syntax with keyof is now utilized to generate mapped types over tuples and arrays.

In Typescript 3.1, mapped object types over tuples and arrays will now create new tuples/arrays instead of transforming them into a new type that converts members like push(), pop(), and length.

Therefore, when dealing with a uniform (homomorphic) mapped type,

type ForwardVal<T> = { 
    [K in keyof T]: string; 
};

If the argument T happens to be a tuple or array type (like in your scenario with ForwardVal<number[]>), only numeric properties are converted as per the documentation, resulting in string[] as the final type.

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

Leverage C# model classes within your Angular application

Just wanted to express my gratitude in advance import { Component, Inject } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-fetch-data', templateUrl: './fetch-data. ...

Enforce Immutable Return in TypeScript

Hello, I am curious to know if there is a way to prevent overwriting a type so that it remains immutable at compile time. For example, let's create an interface: interface freeze{ frozen: boolean; } Now, let's define a deep freeze function: f ...

Retrieve all elements within an Angular6 Directive that share the same name as the Directive

I have created a custom Directive called isSelected and applied it to several elements in different components as shown below: <i isSelected class="icon"></i> <i isSelected class="icon"></i> <i isSelected class="icon"></i ...

How can I obtain my .apk file?

I want to convert my app into .apk format. I inserted the following scripts on my "package.json" page: "build:development:android": "ionic cordova build android" and "build:production:android": "ionic cordova build android --prod --release". However, I ...

Exploring Angular's filtering capabilities and the ngModelChange binding

Currently, I am in the process of working on a project for a hotel. Specifically, I have been focusing on developing a reservation screen where users can input information such as the hotel name, region name, check-in and check-out dates, along with the nu ...

Unable to find the locally stored directory in the device's file system using Nativescript file-system

While working on creating an audio file, everything seems to be running smoothly as the recording indicator shows no errors. However, once the app generates the directory, I am unable to locate it in the local storage. The code I am using is: var audioFo ...

What is the best approach for utilizing Inheritance in Models within Angular2 with TypeScript?

Hey there, I am currently dealing with a Model Class Question and a ModelClass TrueFalseQuestion. Here are the fields: question.model.ts export class Question { answerId: number; questionTitle: string; questionDescription: string; } truefals ...

Is there a way to ensure that in React (Typescript), if a component receives one prop, it must also receive another prop?

For instance, consider a component that accepts the following props via an interface: interface InputProps { error?: boolean; errorText?: string; } const Input = ({error, errorText}: InputProps) => { etc etc } How can I ensure that when this com ...

Invoke a function within the <img> tag to specify the source path

I have been attempting to achieve something similar to the following: <img id="icon" class="cercle icon" src="getIcon({{item.status}})" alt=""> This is my function: getIcon(status){ switch (status) { case 'Ongoing': ret ...

What are the steps to validate a form control in Angular 13?

My Angular 13 application has a reactive form set up as follows: I am trying to validate this form using the following approach: However, I encountered the following error messages: Additionally, it is important to note that within the component, there ...

When working with TypeScript for initial data, you have the choice between using interface types or class types. Which approach is the

When working with initial data in TypeScript, you have the option to use either an interface type or a class type. Which approach is preferable? export interface Item{ text: string, value: number } itemModel: ItemComboBox = { value:'valu ...

What is the purpose of uploading the TypeScript declaration file to DefinitelyTyped for a JavaScript library?

After releasing two JavaScript libraries on npm, users have requested TypeScript type definitions for both. Despite not using TypeScript myself and having no plans to rewrite the libraries in TypeScript, I am interested in adding the type definition files ...

Determining the Clicked Button in ReactJS

I need help with a simple coding requirement that involves detecting which button is clicked. Below is the code snippet: import React, { useState } from 'react' const App = () => { const data = [ ['Hotel 1A', ['A']], ...

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 th ...

What is the process for transforming a JSON object into a TypeScript interface?

After receiving a JSON output from an api: { "id": 13, "name": "horst", "cars": [{ "brand": "VW", "maxSpeed": 120, "isWastingGazoline": true ...

Disabling FormArray on-the-fly in Angular

I have a scenario where I need to disable multiple checkboxes in a FormArray when the page loads. Despite my attempts to implement this, it hasn't been successful so far. Can someone provide guidance on how to achieve this? .ts file public myForm: Fo ...

Importing node_modules in Angular2 using TypeScript

My Angular2 app started off as a simple 'hello world' project. However, I made the questionable decision to use different directory structures for my development environment and the final deployment folder on my spring backend. This difference c ...

Validation in Angular2 is activated once a user completes typing

My goal is to validate an email address with the server to check if it is already registered, but I only want this validation to occur on blur and not on every value change. I have the ability to add multiple controls to my form, and here is how I have st ...

The noUnusedLocal rule in the Typescript tsconfig is not being followed as expected

I am currently working on a project that utilizes typescript 3.6.3. Within my main directory, I have a tsconfig.json file with the setting noUnusedLocals: true: { "compilerOptions": { "noUnusedLocals": true, "noUnusedParameters": true, }, ...

Adding a fresh element and removing the initial item from a collection of Objects in JavaScript

I'm working on creating an array of objects that always has a length of five. I want to push five objects initially, and once the array reaches a length of five, I need to pop the first object and push a new object onto the same array. This process sh ...