Reputation: 2201
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?
Upvotes: 0
Views: 303
Reputation: 1337
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:
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