2
type TypeOfSomething = "something" | "other thing";

interface HigherLevel<T extends TypeOfSomething> {
  subsection: MidLevel<T>;
}
interface MidLevel<T extends TypeOfSomething> {
  callback: (arg: T) => void;
}

const t = { subsection: { callback: (arg: "something") => {} } } as HigherLevel;

This throws an error (typescript error) Generic type 'HigherLevel' requires 1 type argument(s).ts(2314)

Full Error: Generic type 'HigherLevel' requires 1 type argument(s).ts(2314) On the line with as HigherLevel

Why is this? I have specified the type of arg in the callback function so shouldn't typescript be able to infer the type parameter to HigherLevel?

I am using as clause, I get a similar error when using it to type the constant t:

const t: HigherLevel = { subsection: { callback: (arg: "something") => {} } };

It gives me the same error

It would be nice for me to be able to have my types inferred, especially since I am only asking this question as it affects much more complicated typing I am trying to pull off.

I don't know if this is a feature of typescript, but it should be in my opinion or I might be thinking of this problem the wrong way.

Here is a simpler example without the HigherLevel interface, which might be easier to solve. I am looking for a solution to the larger problem above still, but this still confuses me:

type TypeOfSomething = "something" | "other thing";

interface MidLevel<T extends TypeOfSomething> {
  callback: (arg: T) => void;
}

const t: MidLevel = { callback: (arg: "something") => {} };

Same error, same line :(

TS version: 4.7.4 tsc -V

  • 1
    See [this](https://tsplay.dev/m3X7yW) example. `HigherLevel` expects generic argument, it is required, you are notallowed to omit it. If you want to omit, you should specify default generic value like [here](https://tsplay.dev/wXjDQm) – captain-yossarian from Ukraine Oct 01 '22 at 09:01

1 Answers1

1

I generally use functions to infer generic types

function inferType<V extends TypeOfSomething>(t: HigherLevel<V>) { return t }

const t = inferType({ subsection: { callback: (arg: "something") => {} } })

Doubt there's another method

Dimava
  • 7,654
  • 1
  • 9
  • 24
  • Yes I have resorted to doing this, with more complicated nested types it can become a bit verbose but I agree, there is no other method – Smartguy 88 Oct 02 '22 at 10:48