Transform the values in an object using TypeScript without losing type information

Can TypeScript map an object's values to another type based on the actual type of each entry in the result?

To better explain my goal, consider the following scenario:

const obj = {
    a: 1,
    b: true,
    c: "foo"
}

const result = toFunctions(obj)

// The resulting type would be:
{
    a: (input: number) => any // since 'a' was of type number
    b: (input: boolean) => any // since 'b' was of type boolean
    c: (input: string) => any // since 'c' was of type string
}

I aim to leverage the types from the original object's keys to generate the keys in the returned object while applying some form of transformation. In my case, I intend to encapsulate values in functions, but this mechanism could also yield other aggregate types like number[] or string[].

My objective is to create a generic approach to produce function types based on the keys of any object.

Answer №1

Mapped types can solve your problem.

type FunctionMap<T> = {
  [K in keyof T]: (value: T[K]) => any
}

function convertToFunctions<T>(input: T): FunctionMap<T> { … }

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

After upgrading from Angular 13 to 14, the <app-root> component is failing to load. Despite no noticeable changes, the issue persists

Having upgraded my Angular 13 app to version 14, I encountered an issue where the page no longer loads properly. Despite checking the configuration and stripping down the index.html file to its basics, the issue persists - nothing seems to be working. Upo ...

declare wrong TypeScript type in external library

I am currently using winston 3.0 in combination with the @types/winston types. Unfortunately, it seems that these types are not completely compatible, leading to an error in the types that I am unsure how to rectify. Below is the code snippet in question: ...

VPS mysteriously terminates TypeScript compilation process without any apparent error

I've encountered an issue while trying to compile my TypeScript /src folder into the /dist folder. The process works smoothly on my local machine, but when I clone the repo onto my VPS (Ubuntu Server 22.04), install npm, and run the compile script, it ...

Indicate various file formats within the interface

Is there a way to define multiple file types in an interface? interface App { service: Record<ServiceName, Service> } For example, the ServiceName could be Cart, Product, User, etc. And the Service should be an imported object from a .ts file. ...

Using React Material UI in VSCode with TypeScript significantly hampers autocompletion speed

When including the "@mui/material", Visual Studio Code may become unresponsive, leading to Typescript warnings appearing after 10-15 seconds instead of the usual less than 10 milliseconds. For example: import { Button } from '@mui/material&a ...

Ways to boost the smoothlife performance and framerate in p5js

I have a NextJS project using p5js deployed on . This project is an implementation of , which involves a cellular automata generalized on a continuous domain. Currently, it runs at around 10 to 14 frames per second and I aim to increase this. You can fin ...

Exploring NuxtJS Vuex Module namespaces and mutation enumerations

My NuxtJS website has a Vuex store with a root state and a module located at store/shop/cart/state.ts. Within the module, there is a file called store/shop/cart/mutations.ts. import { MutationTree } from 'vuex'; import { CartState } from './ ...

Pause until the user selects either the confirm or deny option before proceeding with the next action

As a beginner in Angular, I am seeking help with my code structure. I have three files: WarningComponent (which displays a warning modal using Bootstrap), modalService (responsible for opening modals), and votingComponent. Within the votingComponent, ther ...

Simulating service calls in Jest Tests for StencilJs

When testing my StencilJs application with Jest, I encountered an issue with mocking a service class method used in a component. The service class has only one function that prints text: The Component class: import {sayHello} from './helloworld-servi ...

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...

Switch statement with reduced scope for factory

How can I narrow the type output of a factory create method using literal types? I've tried narrowing with if statements and discriminated unions, but since this is a creational method, I'm not sure if it's possible. class Radio { type: ...

Angular 6 combined with Firebase is experiencing difficulties with routing after a successful login

After spending hours trying to fix my issue, I still can't figure it out. I've searched through related threads on SO, but haven't found a solution yet. Issue After successfully signing up, the email verification flag is set to true. Howev ...

Navigating the world of TypeScript and SystemJS without the confines of Angular

Lately, I've been delving into TypeScript through research and simple "hello world" projects. However, I've hit a roadblock when it comes to using System.js with TypeScript that I just can't seem to overcome. Most tutorials and demos online ...

In the given situation, which would be the preferable option - making use of useEffect or opting for

My custom hook fetches data from a smart contract as shown below: export const usePoolLength = () => { const [length, setLength] = useState(0); const _getPoolLength = useCallback(async () => { const poolLength = await getPoolLength() ...

Choose a date range from the date picker

I am currently attempting to combine two dates using a rangepicker. Below is the command used to select the date: Cypress.Commands.add('setDatePickerDate', (selector, date) => { const monthsShort = [ 'janv.', 'févr.& ...

Transform the date format from Google Forms to TypeScript

I am currently facing an issue with a Google Form connected to a Google Spreadsheet. The date format in the spreadsheet appears as follows when a response is received: 20/02/2023 18:58:59 I am seeking guidance on how to convert this date format using Type ...

Can a decorator be added to a Typescript class after it has been created?

Is it possible to update a class with inversify's @injectable decorator after it has been created? My use case involves using a mocking library like ts-auto-mock to generate a mock for me, and then applying the @injectable decorator to bind the mock t ...

Encountering a 404 (Not Found) error while trying to access a null resource in Angular at http://localhost

Currently, I am developing an angular application with ng9. I have a specific div where I need to display an avatar using an image fetched from the API in my component.ts file: .... export class HomeComponent implements OnInit { nextLaunch$: Observabl ...

Determine the data type of a variable in TypeScript by utilizing the compiler API

I am facing an issue with retrieving the type of a variable using the compiler API. Here is some background information on my situation: Since I execute everything in memory, I have had to create my own compiler host. This is necessary because the typechec ...

Arranging a dictionary by its keys using Ramda

My task involves manipulating an array of items (specifically, rooms) in a program. I need to filter the array based on a certain property (rooms with more than 10 seats), group them by another property (the area the room is in), store them in a dictionary ...