Typescript declaration for a Record containing a specified set of fields

I am working on the code below:

type MyDict = {
  [k: string]: unknown;
};

function fn<T extends MyDict>(items: T) {
  const functionDict: { [k: string]: (val: keyof T) => void } = Object.fromEntries(
    Object.keys(items).map((key: keyof T) => [
      key,
      (val: keyof T) => console.log(val),
    ]),
  );
}

Is there a way to explicitly declare functionDict as an object (or a Record<>) with keys that are specifically key of T instead of the generic type string?

For example, if I use

type MyExtendedDict = MyDict & {
  foo: number;
  bar: number;
}

fn<MyExtendedDict>({
  foo: 1,
  bar: 2
})

I want to clearly specify that the dictionary's keys should be "foo" and "bar".

Answer №1

It appears that no matter the scenario, Object.fromEntries will consistently use strings as keys.

A viable resolution:

function customFunction<T extends Record<string, any>>(items: T) {
  const entries = new Map<keyof T, (val: T[keyof T]) => void>(Object.keys(items).map((key: keyof T) => [
      key,
      (val: T[keyof T]) => console.log(val)
    ]))
    
  const functionDictionary = Array.from(entries).reduce((obj, [key, value]) => {
    obj[key] = value
    return obj
  }, {} as Record<keyof T, (val: T[keyof T]) => void>);

  return functionDictionary;
}

customFunction({
  foo: 1,
  bar: 2
})

What is returned by Typescript:

function customFunction(items: {
    foo: number;
    bar: number;
}): Record<"foo" | "bar", (val: number) => void>

playground

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

Can type information be incorporated during compilation?

Consider the code snippet below: function addProperties(keys: String[]): Object { // For illustration purposes, this is a specific return return { firstProperty: "first_value", secondProperty: "second_value" }; } export defaul ...

Guide to sending jQuery data back to main class in TypeScript

Hi everyone, I'm diving into the world of typescript and JQuery. I have a simple question. In my typescript class called DatePicker, I am calling a function. Here's a snippet of the code: Class DatePicker { private pickerData; public update( ...

Unable to retrieve files from public folder on express server using a React application

The Issue When trying to render images saved on the backend using Express, I am facing a problem where the images appear broken in the browser. Despite looking for solutions to similar issues, none have resolved the issue for me. Specifics In my server.t ...

When utilizing Typescript to develop a form, it is essential to ensure that the operand of a 'delete' operator is optional, as indicated by error code ts(279

Can someone help me understand why I am encountering this error? I am currently working on a form for users to submit their email address. export const register = createAsyncThunk< User, RegisterProps, { rejectValue: ValidationErrors; } > ...

Emphasize the text based on the content in Angular

database of customers check customer records customer service module access service details component for user details display view user details component 1 view user details component 2 template file for user details component see HTML template Seek ...

Incorporating HTTP status codes into error handling

I have developed an API where I've organized the services separately from the controllers. In my service functions, I've included basic checks to trigger errors when certain conditions are met. Currently, my controller function just returns a 500 ...

What is the best way to display various components based on the user's device type, whether it be web

How can I use Angular 7, TypeScript, bootstrap, ngx-bootstrap, etc., to switch between components based on the user's device (desktop vs mobile)? I have noticed that many websites display different components when resized. I wonder if these are simpl ...

Error in TypeScript: It is not possible to use a component with MUI styling as a JSX element

I can't figure out what's going wrong. I'm attempting to include a child component in the main page, and I have a feeling it has something to do with MUI styles being applied at the end. I removed all unnecessary code and still encounter thi ...

The Angular Ngrx store function, store.select('selector name'), should ideally provide a list of Books but instead, it is returning a non-iterable list

Can someone help me troubleshoot this issue? It's my first time using state management. The result I get when trying to fetch it from the state is not what I expected. Here is the reducer: import {createReducer, on} from '@ngrx/store'; imp ...

What is the best way to delay a recursive JavaScript function for 3 seconds?

Before writing this post, I have already come across the following questions: how-to-pause-a-settimeout-call how-to-pause-a-settimeout-function how-to-pause-a-function-in-javascript delay-running-a-function-for-3-seconds Question The below code snipp ...

Using an exported function with parameters as a filtering mechanism for the material datepicker

I am currently facing an issue while trying to set a const exported function in a material datepicker filter with parameters. When I try to set the parameters in my component, the function gets executed and returns the result (a boolean) instead of simply ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...

Disable and grey out the button while waiting for the Observable to broadcast successfully

component.html <button mat-raised-button color="primary" type="submit"> <mat-icon>account_box</mat-icon> <span *ngIf="!loading">&nbsp;&nbsp;&nbsp;Register</span> <span * ...

How to Connect to Printer in Ionic 2

Does anyone know if there is an option to implement printing/connecting a printer from Ionic 2? Is there a Cordova plugin available for printing? I found this plugin: Cordova Print plugin Any help/information on this would be greatly appreciated. Also, i ...

Testing TypeScript using Jasmine and Chutzpah within Visual Studio 2015

I am new to unit testing in AngularJS with TypeScript. I have been using jasmine and chutzpah for unit testing, but I encountered an error "ReferenceError: Can't find variable: angular". My test file looks like this: //File:test.ts ///<chutzpah_r ...

What is the correct way to implement Vue.use() with TypeScript?

I am trying to incorporate the Vuetify plugin into my TypeScript project. The documentation (available at this link) suggests using Vue.use(), but in TypeScript, I encounter the following error: "error TS2345: Argument of type '{}' is not assign ...

What's the alternative now that Observable `of` is no longer supported?

I have a situation where I possess an access token, and if it is present, then I will return it as an observable of type string: if (this.accessToken){ return of(this.accessToken); } However, I recently realized that the of method has been deprecated w ...

What is the best approach to incorporate a refresh feature for a data stream?

I need to implement a function that updates the current list of items$ and allows for awaiting refreshItems(). This is my working implementation: private readStream = new Subject<T[]>(); readStream$ = this.readStream.asObservable(); getItems = (): ...

Is there a way to retrieve all IDs within an array of objects using a foreach loop and merge the data associated with each ID?

I am currently working on a TypeScript API where I have merged all the data from this API with some additional data obtained from another API function. I have provided a snippet of my code which adds data to the first index of an array. M ...

Replace Material UI propTypes with new definitions

I am currently working with React, Typescript, and Material UI. To globally disable the ripple effect for the ListItem component, I am using createMuiTheme.props in the following manner: createMuiTheme({ props: { MuiListItem: { disableRipple: t ...