typescripttypestype-inferencefunction-signature

TS: Type inference across multiple interfaces and function signature not inferring?


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


Solution

  • 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