deduce the parameter types of a function using the keys of an object

In the following code snippet, my goal is to have the argument type of fn inferred based on the values provided in args.

I aim for good to be automatically inferred as boolean, num as a number and bad to trigger an error.

Currently, all of them are considered as having the type string | number | boolean, without any errors being raised.

type CustomizeArgs<
  Args extends {
    [key: string]: { value: [string, string | number | boolean] };
  } = {
    [key: string]: { value: [string, string | number | boolean] };
  },
  Arg extends keyof Args = keyof Args
> = {
  args: Args;
  fn: (params: { [key in Arg]: Args[Arg]["value"][1] }) => void;
};

const configurations: WithArgs[] = [{
  args: { good: { value: ["bool", true] } },
  fn: ({ good, bad }) => {}
}, {
  args: { num: { value: ["number", 5] } },
  fn: ({ num }) => {}
}];

Answer №1

When working with Typescript, it's important to remember that types can only be inferred for functions. If you are trying to type something other than a function, your generic type will need to take in an argument.

In the provided code snippet, if the first argument is given for the type, then the value of good can only be true. Any reference to bad will result in an error saying "TS2339: Property 'bad' does not exist on type '{ good: true; }'".

const configs: WithArgs<{ good: { value: ['bool', true] } }>[] = [{
  args: { good: { value: ["bool", true] } },
  fn: ({ good, bad }) => {}
}];

It may seem unusual to structure your code in this way, but it highlights the intricacies of TypeScript and its type inference abilities.

In a playground link shared for demonstration purposes,

...

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

Utilizing the power of generics alongside index type manipulation

After successfully running this code: const f = <T extends string>(x: T) => x; f(""); interface Dictionary<T> { [key: string]: T; } const dict: Dictionary<number> = { a: 1 }; I anticipated the following code to work as well: interf ...

Why doesn't TypeScript automatically determine the prop type when Generics are used?

Below is the code snippet: interface MyInterface { a: { b: { c: "c"; }; }; } type ParentProps = keyof MyInterface type ChildProps<ParentProp extends ParentProps> = keyof MyInterface[ParentProp] type GrandChildType< ...

Struggling to retrieve the most recent emitted value from another component in Angular?

Hello everyone, I am currently attempting to retrieve the most recent updated value of a variable from the component app-confirm-bottom-sheet in the app-bene-verification.ts component, but unfortunately, I am unable to achieve this. Below is the code snipp ...

Automating a login prompt with dual inputs using WebdriverIO: A step-by-step guide

I'm having trouble automating the login prompt as shown in the attached image. I've attempted to fill in both fields using WebdriverIO but so far have been unsuccessful. I explored using alert methods like browser.sendAlertText(), but none of the ...

Variations in key options based on specific situations

Is it possible to make certain keys required in Typescript depending on the circumstances? For instance interface IDog { name: string; weight: number; } class Retriever implements IDog { name = "Dug"; weight = 70; public updateAttribute(props ...

Determine the return type based on the input parameter and a mapping strategy

I am encountering an issue with the inferred returnType of the following types. The problem lies in the cityAttractions type, where it should ideally have a type error in its return statement for returning a string instead of an array of strings. Playgrou ...

Connecting the list elements to the current state

My React component is defined as: export default class App extends React.Component<AppProps, Items> The Items class is declared as: export default class Items extends Array<Item> where Item is a class with various properties. When I direct ...

The specified 'IArguments' type does not qualify as an array type

Currently working on crafting a personalized logger. It's a fairly straightforward process, but I'm running into some errors that are muddying up my output. Here's what I have so far: @Injectable() export class Logger { log(...args: any ...

Pagination feature in MUI DataGrid table is malfunctioning

I'm struggling to get the pagination feature to work in my Material UI DataGrid component, but I'm hitting a roadblock: https://i.stack.imgur.com/eT7s7.gif The console is not showing any errors. Here is the code for my component: import { ...

What methods can be used to accurately display the data type with TypeOf()?

When working with the following code: const data = Observable.from([{name: 'Alice', age: 25}, {name: 'Bob', age: 35}]); console.log(typeof(data)); The type is displayed as Object(). Is there a way to obtain more specific information? ...

I encountered a problem where the error "Type '(err: Error) => void' does not possess any properties similar to type 'QueryOptions'" appeared, and I am unsure of the underlying cause

Check out my route for removing a user: https://i.stack.imgur.com/fevKI.png I've set up a route called "/deleteuser" that uses the POST method. It validates the request body for an id and then proceeds to delete the user with that ID from the databas ...

The `setState` function is failing to change the current value

I'm having an issue with setting State in the dropdown component of semantic-ui-react while using TypeScript in my code. The selected category value is always returning an empty string "". Any suggestions on how to resolve this problem? impo ...

Transform object properties into key-value objects using Typescript generics

When I receive a sorting object with a columnName and direction, I want to convert it into a key-value object for mongoose sorting. The return values are not matching up and I can't seem to figure out what I'm missing. These are the interfaces ...

The initial function is executed only after the second function has completed, as it relies on the

For a small project of mine, I've been attempting to load JSON data. However, the issue arises when the loadDefs function is executed before checking if file_data has been modified. loadDefs(file_path:any) { let file_data:string = '&a ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

Encountering HttpErrorResponse when sending a Delete request in Angular

I need help troubleshooting an issue with sending a Delete request from my movie.component.ts file to delete a review. Unfortunately, I keep receiving the dreaded HttpErrorResponse error. Can anyone pinpoint where I may be making a mistake? Take a look at ...

What are the best practices for establishing a secure SignalR client connection?

While tackling this issue may not be solely related to SignalR, it's more about approaching it in the most efficient way. In C#, creating a singleton of a shared object is achievable by making it static and utilizing a lock to prevent multiple threads ...

Why isn't my component calling the service.ts file?

In my Angular project, I am working on a home component that contains a specific method. This method is defined in a service file called service.ts and imported into the homecomponent.ts file. The method is named filterClicked with a condition within the s ...

Instructions on utilizing type interfaces for prop drilling in my React Typescript counter

I am currently developing a basic counter app to monitor my progress in a digital card game that I enjoy playing. While attempting to pass props from the parent component to the child component, I encountered an issue where the props were not being success ...

Managing unpredictable fields within a TypeScript interface Let me known if you need further assistance

Currently, I am developing a web application using Angular and encountered an issue with the JSON data returned by a service call. The problem arises when the mapped JSON contains an Object within one of the fields with unpredictable content. How can I han ...