samedi 27 juin 2020

TypeScript: Return type of combined generic type is always unknown

I want to create a settings store. The user can add a setting with a value of any type. Then he can retrieve a value and get it correctly typed.

My thinking was: this sounds like connected generic type arguments. The type of the result is dependent on the type of the argument to the getSetting() method. So I tried creating said getSetting() method such that it takes a type as input, and based on that type it should be able to infer the return type. This approach uses the type as a key to get the correct information.

Below is my current approach. It seems to be somewhat close to what I want, but the return type of getSetting is always unknown. In the example I would expect it to be number, though.

abstract class Setting<T> {
  abstract value: T;
}
class SD extends Setting<number> {
  value = 0;
}

let getSetting = <T extends Setting<K>, K>(type: new () => T): K => {
  // return value somehow
};

let setting = getSetting(SD); // type of setting is unkown instead of number

Where is my error? Or is there a completely different way to achieve something like this?

Aucun commentaire:

Enregistrer un commentaire