Why does this generic function work for arrays but fail for strings, even though both have slice()?

2 weeks ago 18
ARTICLE AD BOX

I am trying to understand TypeScript generic constraints and type inference.

I have the following function:

function cutValue<T extends { slice(start: number, end?: number): T }>( value: T ): T { return value.slice(0, 3); } cutValue("hellosir"); // Error

When I call it with an array, it works as expected:

cutValue([3, 4, 5, 6, 7]); // OK

But when I call it with a string, TypeScript reports an error:

cutVal("hellomadam"); // Error -> Argument of type 'string' is not assignable to parameter of type '{ slice(start: number, end?: number | undefined): "hellosir"; }'.

Both string and Array have a slice() method, so I expected both calls to work.

Why does TypeScript accept the array case but reject the string case? What is the difference in how TypeScript infers the generic type T in these two situations?

Read Entire Article