To choose types conditionally from another type, you can use the extends
keyword to conditionally check if a particular condition is being satisfied by the target type followed by the ?
symbol (question mark), then the type
to choose when the condition becomes true
, then the :
symbol (colon), and finally the type
to choose when the condition becomes false
.
TL;DR
// a simple interface
interface Person {
name: string;
age: number;
}
// conditionally choose the type `string`
// when the condition becomes `true`
// or choose the type `number`
// when the condition becomes `fasle`
type ConditionalType = Person extends { name: string } ? string : number;
/*
CONCLUSION: 👆
If you hover over the `ConditonalType` type alias
we can see that the type is `string` since the
`Person` interface has a property
called `name` with the type of `string`
*/
To relate it in the JavaScript world, we have an operator called conditional ternary operator
which has the same mechanism we discussed for the type conditional check.
For example, let's say we have an interface
called Person
with some properties like name
having the type of string
and another property called age
having the type of number like this,
// a simple interface
interface Person {
name: string;
age: number;
}
Now we aim to choose either the string
type if the condition is true
or the number
type if the condition is false
by checking if the target type has a property of name
with the type of string
. In our case, the target type is the Person
interface.
So to do that first we can make a new type alias called ConditionalType
followed by writing the target type name Person
followed by the extends
keyword then the condition to check in our case is to check the property of name
having the type of string
({ name: string }
).
After the condition, we can write the type string
to choose when the condition becomes true
followed by the :
symbol and then the type number
to choose when the condition becomes false
.
It can be done liek this,
// a simple interface
interface Person {
name: string;
age: number;
}
// conditionally choose the type `string`
// when the condition becomes `true`
// or choose the type `number`
// when the condition becomes `fasle`
type ConditionalType = Person extends { name: string } ? string : number;
/*
CONCLUSION: 👆
If you hover over the `ConditonalType` type alias
we can see that the type is `string` since the
`Person` interface has a property
called `name` has the type of `string`
*/
As you can see that the ConditionalType
type alias has the type of string
conditionally chosen since the Person
interface has a property called name
having the type of string
.
We have successfully chosen types conditionally from another type in TypeScript. Yay 🥳!
See the above code live in codesandbox.
That's all 😃!