STOP! You better not be individual that I catch using the any
type in my projects. This is only acceptable under very specific circumstances, but should ultimately be eliminated by implementing specific types/interfaces.
Whether you choose to use a type or an interface is mostly a personal preference. However by using a type
you can easily make use of the utility functions that TypeScript has built-in. You could make use of them while using an interface too but the syntax gets ugly quickly.
Some of the mostly used utility types are Pick
, Omit
, Partial
and Record
.
Pick
- Select the keys you want included in the new type.
Omit
- Select the keys you want excluded in the new type.
Partial
- Indicate that all keys of the type are optional.
Record
- Constructs a key/value map type.
For example you might have this type:
type Todo = {
id: string;
title: string;
description: string;
}
but you want to update a todo, but you do not want the id field to be updated, by using the Omit
utility type you can exclude it.
function updateTodo(id: string, updatedTodo: Omit<Todo, "id">) {
// Code to update the todo here
}
updateTodo("todo1", { title: "New title", description: "New description" });
Another example using Record
could be for example:
type PokemonType = "fire" | "water" | "grass";
type PokemonSkill = {
name: string;
damage: number;
}
type PokemonInfo = {
name: string;
health: number;
skills: PokemonSkill[];
}
const pokedex: Record<PokemonType, PokemonInfo[]> = {
fire: [
{
name: "Charmander",
health: 100,
skills: [
{
name: "Solar Power",
damage: 10,
}
]
}
],
water: [],
grass: [],
}
In this example we have mapped a key being the type of pokemon to an array of pokemon info. This could be useful if we for example want to display categories of pokemons depending on what type they are.
an alternative way of writing this without using Record
would be this, however it does not look as good syntax wise:
const pokedex2: { [pokemonType in PokemonType]: PokemonInfo[] } = {
fire: [],
water: [],
grass: [],
}
Want to learn more? Check out the TypeScript documentation!
Top comments (1)
Take your TypeScript skills to new heights with "Mastering TypeScript Core Utility Types":
📖 Buy on Leanpub
📖 Buy on Amazon