Various types of generics within an object

Is there a way to achieve different types for the nested K type within a type like MyType? Here's an example:

type Config<K> = {
  value: K;
  onUpdate: (value: K) => void;
}

type MyType<F extends string> = {
  [K in F]: <V>() => Config<V>;
}

// Desired functionality
const hello: MyType<'setup1'|'setup2'> = {
  setup1: () => ({
    value: { hello: 'world' },
    onUpdate: record => console.log(record.hello),
  }),
  setup2: () => ({
    value: { goodbye: 'world' },
    onUpdate: record => console.log(record.goodbye),
  }),
};

TS Playground

Encountering the error message

Type '{ hello: string; }' is not assignable to type 'V'. 'V' could be instantiated with an arbitrary type which could be unrelated to '{ hello: string; }'.(2322)
when attempting this.

Answer №1

Regrettably, the impossibility arises due to

<V>() => Config<V>
not attributing concrete types to Config, making the generic parameter K in type Config<K> arbitrary and unable to contain any value.

To assist TypeScript in ascertaining the type of K, you must specify during runtime by introducing more generics to MyType. It appears that the key name is the only property varying within your example objects. Therefore, you can define which setup corresponds to which key name like this:

const hello: MyType<{'setup1' : 'hello', 'setup2' : 'goodbye' }> = {

This information can then be interpreted by the types as shown below:

type Config<K extends string> = {
  value: { [F in K]: string };
  onUpdate: (value: { [F in K]: string }) => void;
}

type MyType<F extends { [key: string]: string }> = {
  [K in keyof F]: () => Config<F[K]>;
}

Playground link.

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

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

I'm looking to learn how to implement the delete method in an API using TypeScript. Can anyone help me out

I am seeking guidance on utilizing 'axios' within 'nuxt.js'. I have experimented with sample data, and I am particularly interested in learning how to utilize the 'axios' method within 'nuxt.js' using TypeScript. T ...

Ways to verify if TypeScript declaration files successfully compile with local JavaScript library

I have recently updated the typescript definitions in HunterLarco/twitter-v2, which now follows this structure: package.json src/ twitter.js twitter.d.ts Credentials.js Credentials.d.ts My goal is to verify that the .js files correspond correctly ...

Substitute terms in a sentence according to the guidelines

Looking to transform strings based on specific rules? "Hello {{firstName}}, this is {{senderName}}." Consider the following rules: rules = { firstName: "Alex", senderName: "Tracy" } The expected output would be: "Hello Alex, this is Tracy." If yo ...

There seems to be an issue with the React Native FlatList: It appears that there is no overload matching this call and some

I am currently learning React Native and attempting to create a basic chat room application. I am facing an issue with the FlatList component that I can't seem to resolve. Even though I have provided both the data prop and renderItem prop to the FlatL ...

Error: Unable to access null properties while attempting to address Readonly property error by implementing an interface

Here is the code snippet I am working with: interface State { backgroundColor: boolean; isLoading: boolean; errorOccured: boolean; acknowledgment: string; } export class GoodIntention extends React.Component<Props, State> { ... onCli ...

An email value being recognized as NULL

create-employee.html <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <span><input type="text" [required]="!standingQueue" class="form-control" name="exampleInputEmail1" ...

Retrieve selected button from loop typescript

https://i.stack.imgur.com/DS9jQ.jpgI have an array of individuals that I am looping through. It's a bit difficult for me to explain, but I want something like this: <div *ngFor="let person of persons"> {{person.name}} {{person.surname}} <but ...

TSLint Alert: Excessive white space detected before 'from' keyword (import-spacing)

I'm currently using WebStorm and working to maintain a specific code style: However, I encounter an issue where TSLint highlights my spacing and provides the following hint: "Too many spaces before 'from' (import-spacing)". My main ques ...

Include a Custom Button with an Optional Event Handler

I've created a customized material-ui button component: type ButtonProps = { disabled: boolean; text: string }; export function CustomButton({ disabled, text }: ButtonProps) { return ( <Button type="submit" disabled={disabled} ...

Leverage the globalDependencies feature in Angular2 to utilize Typescript tsd files

I am attempting to incorporate typescript tsd's from DefinitelyTyped into an Angular2 project (RC.0), but encountering issues with loading global dependencies properly: typings install --save dt~hellojs --global --save npm install --save hellojs Her ...

Strategies for ensuring that code does not execute in Angular until the API response has been received

Currently, I am facing an issue where I need to wait for data from an API in order to set the value of a variable and use it in an if condition. The problem lies in my uncertainty about how to properly handle this asynchronous task using async and await. ...

The error message indicates a compatibility issue between parameters 'r' and 'a'

Attempting to reproduce the code found in this blog post, but encountering some perplexing errors. import { option, identity, apply } from 'fp-ts'; import type { Kind, URIS } from 'fp-ts/HKT'; import { pipe } from 'fp-ts/lib/functi ...

Determining the Type<> of a component based on a string in Angular 2

Can you retrieve the type of a component (Type<T>) based on a string value? For example: let typeStr: string = 'MyComponent'; let type: any = getTypeFromName(typeStr); // actual type ...

An unfamiliar data type is provided as a number but is treated as a string that behaves like a number

Here is the code snippet in question: let myVar = unknown; myVar = 5; console.log((myVar as string) + 5); Upon running this code, it surprisingly outputs 10 instead of what I expected to be 55. Can someone help me understand why? ...

Retrieve distinct values for the keys from an object array in JavaScript

Here is the structure of my array: const arr1 = [ { "Param1": "20", "Param2": ""8", "Param3": "11", "Param4": "4", "Param5": "18", ...

Group data by two fields with distinct values in MongoDB

I have developed a Typescript Node.js application and I am looking to organize documents by two fields, "one_id" and "two_id", based on a specific "one_id" value. Below is the data within my collection: { "_id":"5a8b2953007a1922f00124fd", "one_id ...

Exploring Local Gems with Google Places API in Ionic 2

I recently integrated the Google Maps API into my app and now I am looking to incorporate Google Places as well. I have managed to successfully implement Geolocation, but I am facing difficulties when trying to perform a nearby search for "supermarkets" in ...

Utilizing TypeScript with Svelte Components

I've been struggling to implement <svelte:component /> with Typescript without success. Here's my current attempt: Presentation.svelte <script lang="ts"> export let slides; </script> {#each slides as slide} & ...

Distinguishing Between TypeScript Interface Function Properties

Could anyone clarify why the assignment to InterfaceA constant is successful while the assignment to InterfaceB constant results in an error? interface InterfaceA { doSomething (data: object): boolean; } interface InterfaceB { doSomething: (data: obje ...