yaquawa
yaquawa

Reputation: 7338

Why should we use the “extends” keyword but not the type itself?

I've read this article https://www.typescriptlang.org/docs/handbook/generics.html#generic-constraints

I'm wondering that why we have to use the extends keyword here?

interface Lengthwise {
  length: number;
}

function loggingIdentity<T extends Lengthwise>(arg: T): T {
  console.log(arg.length); // Now we know it has a .length property, so no more error
  return arg;
}

Why not just do it like this?? What's the difference when I use the extends keyword?

interface Lengthwise {
  length: number;
}

function loggingIdentity(arg: Lengthwise): Lengthwise {
  console.log(arg.length); // Now we know it has a .length property, so no more error
  return arg;
}

Upvotes: 2

Views: 252

Answers (2)

Karol Majewski
Karol Majewski

Reputation: 25820

It's not like you always have to do that. It just happens to be what you want, most of the time.

When you do this:

function loggingIdentity<T extends Lengthwise>(arg: T): T {

then loggingIdentity will return exactly the same subtype of T as it accepted. This is a stronger promise than saying:

function loggingIdentity(arg: Lengthwise): Lengthwise {

which only promises to return a Lengthwise, which doesn't have to match the accepted parameter.

Let me illustrate the point.

interface Lengthwise {
  length: number;
}

declare function generic<T extends Lengthwise>(arg: T): T;
declare function concrete(arg: Lengthwise): Lengthwise;

const myArgument = { length: 1, foo: 'bar '};

const first = generic(myArgument).foo; // string
const second = concrete(myArgument).foo; // Compile-time error — the knowledge of `foo` was lost

As you can see, second has no property called foo on it. concrete only promises to return a Lengthwise, not the exact subtype of Lengthwise provided to it.

Upvotes: 6

Abdelmonaem Shahat
Abdelmonaem Shahat

Reputation: 544

  • the difference is by using extends it means that the generic or whatever is extended can inherit all properties from the interface and add more properties but in the second case you can't add more than length property in the interface. so u can't add more than one property which here is the length property but by using extends you can use as many arguments as you wish beside the properties of the interface.

Upvotes: 0

Related Questions