From the course: Learning TypeScript

Unlock the full course today

Join today to access over 22,700 courses taught by industry experts or purchase this course individually.

Reusing common logic with generics

Reusing common logic with generics - TypeScript Tutorial

From the course: Learning TypeScript

Start my 1-month free trial

Reusing common logic with generics

- [Instructor] In this video, I'm going to show you a slightly more advanced feature of TypeScript called generics, which is a way to decorate a component with a type syntax in such a way that it can describe a variety of types rather than a single one. Take this function for example. It uses the JSON.stringify and parse functions to serialize an object into a string and then parses that string back to create a new object with a structure and data identical to the first. That means if I were to call this function and pass in an inventoryItem object, I would expect that the object that I receive out would be the same type. In this case, cloned should be the type in inventoryItem. But it's not. Even if it might be obvious to us that if you serialize an object and then de-serialize it again, the result should be the same type, TypeScript can't see that because it doesn't know enough about the way that JSON functions…

Contents