Typescript: Defining the type of an object based on its keys' values

I need help figuring out how to define a type for an object that has values dependent on the keys. Check out the code snippet below for a better explanation.

Here is my attempt:

// Given this type
type Mapping = {
  "string": string;
  "number": number;
  "boolean": boolean;
};

// I am attempting to create a type where the keys match those in `Mapping`, but 
// the values are functions with the corresponding value of `Mapping` as the first argument.
type Property<K extends keyof Mapping> = Record<K, (value: Mapping[K]) => void>;

type Obj = Partial<Property<keyof Mapping>>;

const a: Obj = {
  // Currently, Typescript shows `value` as string | number | boolean.
  // My goal is for Typescript to recognize the type of `value` as boolean. 
  boolean: (value) => {
    console.log(value);
  }
}

Typescript Playground Link

Answer №1

Explore the concept of a mapped type

type Mapping = {
    "string": string;
    "number": number;
    "boolean": boolean;
};

type Property<T extends Mapping> = {
    [K in keyof T]: (value: T[K]) => void
}

type Obj = Partial<Property<Mapping>>;

const a: Obj = {
    boolean: (value) => {
        console.log(value);
    }
}

Visit Playground for interactive demo

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

Tips for identifying modifications in a TypeScript object within Angular 6

My dilemma lies in a string harboring error messages. error: String; The task at hand requires toggling the submit button depending on the content of this string. If empty, it should be disabled. How can I track any alterations to the error string in a ...

Angular doesn't support this particular type as an injection token

I'm attempting to create a constructor with a type of string, but I keep encountering the following error: This particular type is not supported as an injection token @Injectable({providedIn: 'root'}) export class DataService { const ...

Experiencing a bug in my express application: TypeError - Unable to access properties of undefined (reading 'prototype')

I've encountered the TypeError: Cannot read properties of undefined (reading 'prototype') error in my javascript file. Despite researching online, it seems that many attribute this issue to importing {response} from express, but I am not doi ...

Tips on providing form validation in Ionic

I'm currently working on a registration form and I need some advice on how to implement custom name and email validation. Here is the structure of my form: registrationForm = this.formBuilder.group({ name: [''], email: ['' ...

Is it necessary to manually unsubscribe from observables in the main Angular component?

I'm facing a dilemma with my Observable in the root Angular (6.x) component, AppComponent. Typically, I would unsubscribe from any open Subscription when calling destroy() using the lifecycle hook, ngOnDestroy. However, since the AppComponent serv ...

Having trouble with Visual Studio 2015 not compiling TypeScript within an ASP.NET Core project?

Seeking assistance with my Angular app development setup in VS2015. Even though it is recognized as a TypeScript Virtual Project, I am facing issues getting the transpiled files into the wwwroot folder within my ASP.NET Core project. Here's an overvie ...

Guide on dividing a URL string in Angular framework

Is there a way to include a value directly in the URL, like so: http://example.com/component/july2021 I need to extract july2021 from the component and separate it into "july" and "2021". How can I achieve this? ...

Typescript: require generic types to include specific keys at all times

Is there a way to ensure that the function below only accepts a data object if it contains an id key, and then allows us to access the id from the data object? function someFuntion<T>(data : T){ const id = data['id'] //Error : Element imp ...

Changing data types conditionally in Angular using TypeScript

My angular component relies on the API Response for its functionality. I receive these responses from an external API. When there are no errors Data : { Status: string; Data: number; } When an error occurs, this is what I get. Data : { Status: string; ...

"Using MatCheckbox's preventDefault() method to access the checked value of the

Is there a way to customize a Material checkbox to prevent it from being checked or unchecked by default (e.g., by calling preventDefault() on the event) and still retrieve the checked value from the event? It appears that achieving both conditions simult ...

The MemoizedSelector cannot be assigned to a parameter of type 'string'

Currently, my setup involves Angular 6 and NgRX 6. The reducer implementation I have resembles the following - export interface IFlexBenefitTemplateState { original: IFlexBenefitTemplate; changes: IFlexBenefitTemplate; count: number; loading: boo ...

Issue with migrating TypeOrm due to raw SQL statement

Is it possible to use a regular INSERT INTO statement with TypeOrm? I've tried various ways of formatting the string and quotes, but I'm running out of patience. await queryRunner.query('INSERT INTO "table"(column1,column2) VALUES ...

Unable to successfully generate work item through VSO SDK

A team is attempting to develop a custom widget on VSTS to facilitate group code reviews. One of the tasks is to create a new work item with the type "Code Review Response" and link it to code changes. However, the current code is not functioning as expect ...

Exploring how to read class decorator files in a Node.js environment

I've developed a custom class decorator that extracts permissions for an Angular component. decorator.ts function extractPermissions(obj: { [key: 'read' | 'write' | 'update' | 'delete']: string }[]) { re ...

Using Typescript with a Node Express router and passing a second argument. Furthermore, utilizing the Typescript-eslint rule for preventing mis

How can I address the registration function to resolve the @typescript-eslint/no-misused-promises issue? I have managed to fix this problem by using eslint in the following way: "@typescript-eslint/no-misused-promises": [ "error", { ...

Is the Vue.js 2.x composition API completely compatible with TypeScript?

After migrating our vue.js 2.x project to typescript, I came across Evan You's comment in this issue: https://github.com/vuejs/rfcs/pull/17#issuecomment-494242121 The Class API proposal has been dropped, so I switched to the regular option-based ver ...

Functions do not retrieve values directly from an array

Here is a code snippet that I have for(var i=0; i < this.arr2.length; i++) { arr.push({ id: i.toString(), label: this.arr2[i], display: () => this.arr2[i] }) } I'm curious why the display is undefin ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...

Creating a spy object in Jest just got easier with the `

If you want to create a spy object with Chai, you can do so by using the following syntax: chai.spy.object([ 'push', 'pop' ]); For jasmine users, the equivalent code would be: jasmine.createSpyObj('tape', ['play', ...

Has anyone made the switch from using exports and require in Typescript to consolidating everything into a single file output?

When we first started our TypeScript project, we used external modules with "require Foo = ('./Foo')" which proved to be very organized and useful. However, it required us to use requirejs (AMD modules) or a similar method. While this wasn't ...