Typescript generics return type issues

Viewed 94

I use typescript generics in my project but it seems not work well.

example:

interface Test<T, P> {
  a?: (v: T) => P
  b?: (v: P) => void
}

const fn1 = <T, P>(_config: Test<T, P>) => {}

fn1({
  a: (p) => 1,
  b: (p) => {},
})

I think params 'a' type just like:

Test<unknown, number>.a?: ((v: unknown) => number) | undefined

But, actually:

Test<unknown, unknown>.a?: ((v: unknown) => unknown) | undefined

I do not know why, someone can help me? Thanks.

2 Answers

Since you are not defining the type on this line: b: (p) => {}

Then TS cannot infer the type of P, even though you return it in the above definition for a.

This is because in a union an unknown absorbs everything.

For P in (a) TypeScript infers a type of "number", but then for P in (b) it infers a type of "unknown", just as it does for T in (a).

Therefore, P results in a "number | unknown" (not "number | undefined" as you expected), which results in just "unknown".

If you refer to the TypeScript docs here, you'll find:

// In a union an unknown absorbs everything

type P = unknown | number; // unknown

Related