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"); // ErrorWhen I call it with an array, it works as expected:
cutValue([3, 4, 5, 6, 7]); // OKBut 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?
