Search code examples
typescripttypescript-genericsgeneric-type-argumentgeneric-type-parameters

Is there a way to have function parameter type based on generic parameter type?


I have a generics parameterize type for a function that returns the property of the global object.

type Store = {
  "first": number;
  "second": boolean;
  "third": string;
}

declare function namespaced<S extends Record<string, any>, N extends keyof S>(namespace: N): S[N];

let p = namespaced<Store, "first">("first");

Since the namespace parameter has type of keyof S, I thought it would be possible to omit the second type in the function definition, and my code would look like this:

let p = namespaced<Store>("first");

However this gives me the error:

Expected 2 type arguments, but got 1.(2558)

Is it possible to achieve it without changing the function?

Playground


Solution

  • No, but you can use currying as an alternative:

    declare function namespaced<S extends Record<string, any>>(): <N extends keyof S>(namespace: N) => S[N];
    
    let p = namespaced<Store>()("first");
    

    Playground