Learn TypeScript
Implementing generic parameter defaults
Implementing generic parameter defaults
In this lesson, we will learn how to define a default on a generic parameter.
Generic parameter default type syntax
A default type can be defined on a generic parameter as follows:
<T = DefaultType>
We specify the default type after the equals (=
) sign after the generic parameter.
Generic parameter defaults can be added to functions, interfaces, type aliases, and classes.
An example
We are going to explore default generic parameters in an exercise.
The code contains a generic function and a generic interface. We are going to explore the generic interface first.
- Copy the code from below into the editor:
const button: Component = { name: "Button", props: { text: "Save", }, log: () => console.log("Save button"),};
This creates an object with the Component
interface.
A type error occurs on the button
variable. Why is this so?
We could of course pass in the types as follows:
const button: Component<string, { text: string }> = ...
... but we aren't going to do that!
- Specify a default type of
string
forT1
in theComponent
interface.
- Specify a default type of
any
forT2
in theComponent
interface.
The type errors have been resolved now.
Nice!
- Add the following code:
1console.log(button.props.text);2console.log(button.props.text2);
Why isn't a type error raised on line 2?
When a generic parameter default is used, the type might be wider than necessary.
Let's move on to explore the generic function.
- Add the following code:
const first = firstOrNull([1, 2, 3]);console.log(first);
We haven't supplied the generic parameter to the function. So, why doesn't a type error occur?
- Specify a default type of
string
forT
in thefirstOrNull
function.
What is the type of the first
variable? This will be inferred from the return type of firstOrNull
.
Summary
Default types for generic parameters can make interfaces, type aliases, and classes easier to consume. It is important to be aware that consuming code can be weaker typed if this approach is used.
Generic functions don't require generic parameters to be passed. TypeScript can generally infer generic parameter types on functions from the parameters passed into it. So, generic parameter defaults aren't that useful on generic functions.
In the next lesson, we will learn how to constrain the type of generic parameters.