2

I have the following types

type CommonDic<Dic> = {
  [I in keyof Dic]: {
    [W in keyof Dic[I]]: string;
  };
};

type MyDic = {
  a: {
    apple: string;
    ant: string;
  };
  b: {
    banana: string;
    bear: string;
  };
};

Problem

const getWord = <D extends CommonDic<D>, T extends keyof D, W extends keyof D[T]>(key: T, word: W) => {
  return {
    key,
    word,
  };
};

const word1 = getWord<MyDic>("a", "apple");
// error TS2558: Expected 3 type arguments, but got 1.

The code below works but any way to do this without currying?

const getWord2 =
  <D extends CommonDic<D>>() =>
  <T extends keyof D, W extends keyof D[T]>(key: T, word: W) => {
    return {
      key,
      word,
    };
  };

const word2 = getWord2<MyDic>()("a", "apple"); // works

I've tried default type parameter but wasn't successful. Thanks!

3
  • Type arguments can be made optional by providing a default type in their declaration. However, if you find yourself passing type arguments explicitly, optional or otherwise, you're doing something wrong in 99.9% of cases. All types in the language are subject to full erasure. You must understand the language before you write code like that. In other words, each type parameter should be inferable from a value parameter otherwise your code is basically wrong Commented Jan 15, 2023 at 16:34
  • 1
    I recently answered another question almost exactly like this. TypeScript doesn't currently allow for supplying only some generic type parameters: it's either all or none at the moment. You can read more about this at the following GitHub issue: microsoft/TypeScript#10571 - Allow skipping some generics when calling a function with multiple generics Commented Jan 15, 2023 at 16:51
  • 1
    Currying is probably the best approach given the absence of partial type argument inference; see the other questions/answers for more information. Commented Jan 15, 2023 at 17:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.