Recently, I came across this interesting article at https://www.typescriptlang.org/docs/handbook/generics.html#generic-constraints
I can't help but wonder why the extends
keyword is necessary in this context.
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length); // By using `extends`, we ensure that it has a .length property
return arg;
}
Is there any significant difference if I were to simply write the function without the extends
keyword like this?
interface Lengthwise {
length: number;
}
function loggingIdentity(arg: Lengthwise): Lengthwise {
console.log(arg.length); // This approach also works fine, but what's the impact of not using `extends`?
return arg;
}