What is the advantage of utilizing the "extends" keyword over directly stating the type?

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;
}

Answer №1

There is no obligation for you to always follow that particular path. It just seems to align with your desires most of the time.

Consider this scenario:

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

In this case, loggingIdentity will yield the exact subtype of T it was given. This commitment goes beyond simply stating:

function loggingIdentity(arg: Lengthwise): Lengthwise {

which only ensures a return type of Lengthwise, without necessarily matching the accepted input parameter.

To clarify this concept, let's look at an example:

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 evident from the code snippet, second does not contain the property foo. The function concrete solely commits to returning a Lengthwise object, without preserving the exact subtype provided as input.

Answer №2

  • When using the extends keyword, the generic or whatever is being extended can inherit all properties from the interface and additional properties can be added. However, in the second case, only the length property can be added to the interface. This means that you are limited to adding just one property, which is the length property. On the other hand, by using the extends keyword, you have the flexibility to add as many arguments as needed along with the properties of the interface.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountered an error while trying to install @material-ui/core through npm: Received an unexpected end of JSON input

npm install @material-ui/core npm ERR! Unexpected end of JSON input while parsing near '...X1F+dSMvv9bUwJSg+lOUX' npm ERR! A complete log of this run can be found in: npm ERR! C:\Users\WR-022\AppData\Roaming\npm-cach ...

Unit testing an Angular service using Jasmine with a JSON object schema in Angular 2/4

Looking for assistance with unit testing a service I have. The service includes a current json array object that is functioning properly when the observable is subscribed to. However, I seem to be encountering issues with my unit test setup. Can anyone pr ...

Utilizing external imports in webpack (dynamic importing at runtime)

This is a unique thought that crossed my mind today, and after not finding much information on it, I decided to share some unusual cases and how I personally resolved them. If you have a better solution, please feel free to comment, but in the meantime, th ...

The data type 'Event' cannot be assigned to the data type 'string' in this context

Recently diving into Angular, I came across a stumbling block while working through the hero tutorial. The error message that popped up was: Type 'Event' is not assignable to type 'string' You can see the error replicated here. ...

When the promise is resolved, the members of the AngularJS controller are now

I'm experiencing some unexpected behavior in my controller when executing a certain method. The code snippet looks something like this: this.StockService.GetByInvoicesID(this.SelectedInvoice.ID).success((StockItems) => { this.StockItems = Stoc ...

Determine the type of function arguments based on provided hints in TypeScript

It's common to encounter situations like this where TypeScript struggles to infer types due to lack of context. Is there a way to explicitly declare the type of function for the compiler? router.get('/get', imget); router.get('/send&a ...

While validating in my Angular application, I encountered an error stating that no index signature with a parameter of type 'string' was found on type 'AbstractControl[]'

While trying to validate my Angular application, I encountered the following error: src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used ...

`Drizzle ORM and its versatile approach to SELECT statements`

Looking to improve the handling of options in a function that queries a database using Drizzle ORM. Currently, the function accepts options like enabled and limit, with potential for more options in the future. Here's the current implementation: type ...

"Encountering a build failure in Next.js when using getStaticProps because a parameter is returning undefined

An unusual error has recently surfaced, causing our builds to fail, Located within the pages directory is a post/[id].tsx file that utilizes getStaticProps and getStaticPaths -- props export const getStaticProps: GetStaticProps = async ({ params }) => ...

Firebase cloud function encountered an issue: Error: EISDIR - attempting to perform an unauthorized operation on a directory

I am currently working on a task that involves downloading an image from a URL and then uploading it to my Firebase cloud storage. Below is the code I have implemented for this process. import * as functions from 'firebase-functions'; import * a ...

Creating a function in TypeScript that returns a string containing a newline character

My goal is to create a function that outputs the text "Hello" followed by "World". However, my current implementation does not seem to be working as expected. export function HelloWorld():string{ return "Hello"+ "\n"+ "W ...

Executing an HTTP POST request without properly encoding a specific parameter

I am attempting to communicate with an unauthorized third-party API using Node and the request module. Below is the code that generates the request: request.post( { url: url, headers: MY_HEADERS_HERE, followAllR ...

Unexpected outcome in Typescript declaration file

This code snippet is dealing with the 'legend' function: legend = (value) => { return typeof value === 'boolean' ? { 'options.legend.display': value } : { 'options.l ...

Utilizing ngx-logger Dependency in Angular 6 for Efficient Unit Testing

Have you ever attempted to test classes in Angular that rely on ngx-logger as a dependency? I am looking for guidance or examples of how this can be achieved using testing frameworks such as Jasmine. It seems there are limited resources available on mock ...

How can an array be generated functionally using properties from an array of objects?

Here's the current implementation that is functioning as expected: let newList: any[] = []; for (let stuff of this.Stuff) { newList = newList.concat(stuff.food); } The "Stuff" array consists of objects where each ...

When should you utilize the Safe Navigation Operator (?.) and when is it best to use the Logical AND (&&) operator in order to prevent null/undefined references?

Imagine having an object property (let's call it arrThatCouldBeNullOrUndefined: SomeObjType) in your Angular component. You aim to perform an array operation (let's say filter() operation) on its data: DataType[] object and save the result in an ...

The Angular Date Pipe is currently unable to display solely the Month and Year; it instead presents the complete date, including day, month,

I'm currently using the Bootstrap input date feature to save a new Date from a dialog box. However, I only want to display the month and year when showing the date. Even though I added a pipe to show just the month and year, it still displays the mont ...

Converting and Casting Enums in TypeScript

Is there a way to convert one enum into another when they have the same values? enum Enum1 { Value = 'example' } enum Enum2 { Value = 'example' } const value = Enum1.Value const value2 = value as Enum2 ...

Deactivate multiple textareas within a loop by utilizing JQuery/Typescript and KnockoutJS

I am working on a for loop that generates a series of textareas with unique ids using KO data-binding, but they all share the same name. My goal is to utilize Jquery to determine if all the textareas in the list are empty. If they are, I want to disable al ...

Tips for streamlining the use of http.get() with or without parameters

retrievePosts(userId?: string): Observable<any> { const params = userId ? new HttpParams().set('userId', userId.toString()) : null; return this.http.get(ApiUrl + ApiPath, { params }); } I am attempting to streamline the two http.get ca ...