R
R
raury2021-10-21 23:24:54
typescript
raury, 2021-10-21 23:24:54

Why is the variable type unknown?

Why is val type unknown and not string? Version ts - 4.1.2

type A<T> = T extends (param: infer R) => void ? R : string;

type F = () => void

let val: A<F>;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2021-10-22
@raury

Firstly, infer participates in the predicate itself as any
Secondly, a function with fewer arguments is a subtype for a function with a large number of arguments (this allows, for example, to send a function to the callback that does not use all the arguments passed to it)
That is, the type () => voidis a descendant of type (param: any) => void, which means that your predicate in type A becomes true and goes to the branch, where you return R from infer, which is inferred to the top of the hierarchy - type unknown
What you have in mind can be done like this:

type A<T> = T extends (...param: infer P) => void
  ? P extends [infer R, ...unknown[]]
    ? R
    : string
  : string;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question