Learn TypeScript

Creating generic type aliases

Creating generic type aliases

We can use generics in type aliases as well as interfaces. In this lesson, we will learn how to do this.

Generic type alias syntax

We can pass types into an type alias using the following syntax:

type TypeName<T1, T2, ...> = {
...
}

The members of the type can reference the generic types passed into it.

Generic type alias example

We can use a type alias to build the generic form we built using an interface in the last section.

TypeScriptOpen exercise in CodeSandbox

The Contact interface and contactForm variable remain the same as the last lesson. So these have already been implemented in the code.

  • Try to build the Form type using a type alias in the code editor.

Summary

Generic type aliases are just like generic interfaces with a slightly different syntax. Generally, it is a personal preference which approach you use to create generic types.

Great stuff, we are getting comfortable with generics now!

In the next section, we'll learn all about generic classes.

Did you find this lesson useful?

Share this lesson on twitter
© 2024 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more