Shivam Singla
Shivam Singla

Reputation: 2201

Why typescript compiler is not inferring generic parameter?

I have this code

type Check<F, T> = F extends string
  ? string
  : T

type Func2 = <F extends T[] | string, T>(functor: F) => Check<F, T>

const x: Func2 = (x: any) => x[0]

const y = x([1, 2])
const z = x("abc")

I am getting type unknown for y while it is perfectly fine for z.

The type inferred for calling x for y is -

const x: <number[], unknown>(functor: number[]) => unknown

Why there is unknown for T but T[] is inferred properly?

Playground

Upvotes: 0

Views: 303

Answers (1)

Why does this happen?

Type inference in TS doesn't work as you expect. Type variables could be inferred as I think in three ways:

  • based on an argument of a function that has been passed;
  • based on analysis of return value of a function;
  • based on previously inferred type variables (this rule applied only from left to right order);

That's why you have got unknown type.


Solution in your case could be:

type Check<F, T> = F extends (infer U)[]
  ? U
  : T

type Func2 = <F extends any[] | string>(functor: F) => Check<F, string>

const x: Func2 = (x: any) => x[0]

const y = x([1, 2])
const z = x("abc")

Upvotes: 2

Related Questions