With a simple construct like this:
type Test<Source extends string[]> =
Source extends [infer Head, ...infer Tail] ? `${Head}${Head}` : never;
Typescript complains about the string interpolation inside ${Head}${Head}
saying: Type `'Head'` is not assignable to type 'string | number | bigint | boolean'. Type 'Head' is not assignable to type 'number'.ts(2322)
...which does not make much sense to me but my searches did not turn fruitful. Source must be a string[]
so Head
, if it exists, must be a string right? So ${Head}
must be totally valid. Why is TS complaining about not being able to assign it to a number
? String is also assignable to "string | number | bigint | boolean"
so this error does not make much sense to me. I can fix it by putting the string interpolation between a "Head extends string ? ... : ...
clause but I am wondering why it is necessary in the first place.
Yes and no. Take a look on next example:
type Test0<Source extends string[]> =
Source extends [infer Head, ...infer Tail] ? Head : never;
type O = Test0<[never, 'a']> // no error, because that is how NEVER works
Because string|never
returns string
.
I think it is much safer to check if Head is string or not in above case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With