4 TypeScript Concepts Every Developer Should Know
In this post, we’ll explore four TypeScript concepts: discriminated unions, utility types, generics, and the differences between as, satisfies, and is. We’ll learn what they are, how they work, and how they help us write safer code through practical examples.
- Published
- Published:
- Updated
- Updated:
- minute read
- 11 minute read
Hello everyone and welcome to my first blog.
In this blog we want to discuss 4 TS concepts that every developer should know and I think are very necessary for writing good code and type-safe projects. These 4 concepts are:
- Discriminated Unions
- Utility Types
- Generic Types
- The Difference between 'as', 'satisfies' and 'is'
#Discriminated Unions
Let’s assume that you have a task to fetch posts from an API and show a list of them on your page. To keep the examples simple, each post has 4 properties:
- id
- title
- body
- published
A normal developer might just use parameters and write these types to track the request with a loading flag, an optional posts array and an optional error message.
type Post = {
id: string;
title: string;
body: string;
published: boolean;
};
type PostState = {
loading: boolean;
posts?: Post[];
error?: string;
};
If you think this is fine, I have to tell you that you are not wrong and this can definitely do the job, but the question is how to prevent the front-end bugs we might have. This kind of writing allows combinations that may not make sense for the UI. For example, we could accidentally set loading to true while also providing an error message:
const state: PostState = {
loading: true,
error: "Failed to fetch posts",
};
It also allows loading to be false without providing either posts or an error. We have to decide what each combination means, and to do so, we use the discriminated unions like these:
type PostState =
| { status: "idle" }
| { status: "loading" }
| { status: "success"; posts: Post[] }
| { status: "error"; message: string };
The shared status property is the discriminant. And the PostState can only be one of these. It will help prevent mistakes that we might make when writing the component UI. For example, in this type, the success variant provides posts, while the error variant provides a message. This helps us handle posts and error messages in their relevant states. Checking status also helps TypeScript understand which properties are available:
if (state.status === "success") {
console.log(state.posts.length);
}
This is called narrowing. Inside this condition, TypeScript knows that state is the success variant. We still need to update the state when the request starts, succeeds, or fails, and validate the data returned by the API. The discriminated union helps us describe those states clearly and catch mistakes in how our code creates and uses them.
#Utility Types
Now let’s move to utility types. These help us create new types from existing ones without writing the same properties again. There are 22 of them including the string-manipulating ones:
| Utility | Purpose |
|---|---|
Partial<T> |
Makes properties optional |
Required<T> |
Makes properties required |
Readonly<T> |
Makes top-level properties read-only |
Pick<T, K> |
Keeps selected properties |
Omit<T, K> |
Removes selected properties |
Record<K, T> |
Maps keys to a value type |
Exclude<T, U> |
Removes union members assignable to U |
Extract<T, U> |
Keeps union members assignable to U |
NonNullable<T> |
Removes null and undefined |
Awaited<T> |
Recursively unwraps promise-like types |
Parameters<T> |
Gets function parameter types as a tuple |
ReturnType<T> |
Gets a function’s return type |
ConstructorParameters<T> |
Gets constructor parameter types as a tuple |
InstanceType<T> |
Gets a constructor’s instance type |
NoInfer<T> |
Blocks inference from that type position |
ThisParameterType<T> |
Gets a function’s explicit this type |
OmitThisParameter<T> |
Removes a function’s explicit this parameter |
ThisType<T> |
Marks a contextual this type |
Uppercase<S> |
Uppercases a string literal type |
Lowercase<S> |
Lowercases a string literal type |
Capitalize<S> |
Uppercases its first character |
Uncapitalize<S> |
Lowercases its first character |
But here we will discuss four of them which I think are the most useful and important: Omit, Pick, Partial and Record.
#Omit
Let’s assume that we want to create a post and the backend generates its id. We can use Omit to leave that property out of our input type:
type CreatePost = Omit<Post, "id">;
This gives us a type that is equal to:
type CreatePost = {
title: string;
body: string;
published: boolean;
};
We can also omit more than one property by using a union of their names:
type PostContent = Omit<Post, "id" | "published">;
Here, PostContent only has title and body.
#Pick
Now let’s assume that we want to show a post card and only need its id and title. Instead of removing the other properties, we can pick the ones we need:
type PostCard = Pick<Post, "id" | "title">;
This gives us a type that is equal to:
type PostCard = {
id: string;
title: string;
};
Omit leaves out selected properties, while Pick keeps selected properties.
#Partial
When updating a post, we might only want to change one property. We shouldn’t have to provide the title, body and published value every time.
Partial helps us by making every property optional:
type UpdatePost = Partial<CreatePost>;
This gives us a type that is equal to:
type UpdatePost = {
title?: string;
body?: string;
published?: boolean;
};
Now we can provide just the properties we want to update:
const titleUpdate: UpdatePost = {
title: "A Better Title",
};
const publishUpdate: UpdatePost = {
published: true,
};
We can also combine Partial and Omit together:
type UpdatePost = Partial<Omit<Post, "id">>;
Here, we first remove id and then make the remaining properties optional.
One important thing to remember is that Partial also allows an empty object:
const emptyUpdate: UpdatePost = {};
Because every property is optional, none of them must be provided. If we require at least one field, we need an additional check (for example, a function to check the emptiness) or a more specific type.
#Record
Let’s assume that we want a text label for each request status from our previous example:
type RequestStatus = "idle" | "loading" | "success" | "error";
const statusLabels: Record<RequestStatus, string> = {
idle: "Ready to load",
loading: "Loading posts",
success: "Posts loaded",
error: "Something went wrong",
};
Record lets us describe an object’s keys and the type of its values. Here, every RequestStatus must have a string label. If we forget one of these statuses, TypeScript will report an error.
These utilities help us reuse our existing types and describe the data needed for different tasks. But they only work at the type level. Omit does not delete properties from an actual object, and Pick does not automatically select fields from an API response.
#Generics
This could be the scariest topic in TypeScript that any developer should confront sooner or later.
Generics are mostly used for the types that we cannot determine exactly. For example, think of a function that always returns the first element of an array.
function first(items) {
return items[0];
}
const title = first(["TypeScript", "JavaScript"]);
Now if we want to write the TS version of this function, we might use string for the type of an array but what if our array is a list of numbers? Or we can use any for the type of the array but it's obviously not best practice. For this kind of situation we use generic types. And how do we do it?
function first<ArrayType>(items: ArrayType[]): ArrayType| undefined {
return items[0];
}
first([10, 20]);
And now if we hover on the "first", the type of it is number.
We can also give the function the types ourselves using:
first<number>([10, 20]);
The generics are not limited to functions. Suppose different API operations share a response structure like this:
type ApiResult<T> =
| { ok: true; data: T }
| { ok: false; error: string };
And this way we can handle our API responses type safely. We can use this structure with different data:
type Product = {
id: string;
name: string;
price: number;
};
const productResult: ApiResult<Product> = {
ok: true,
data: {
id: "product-1",
name: "Keyboard",
price: 100,
},
};
const titlesResult: ApiResult<string[]> = {
ok: true,
data: ["TypeScript", "JavaScript"],
};
But there is a thing to keep in mind: An unconstrained T could be a number, a string, an object, or something else. So we cannot write:
function getLength<T>(value: T): number {
return value.length; // Error: T might not have length.
}
This is because the value can be a number, and a number does not have length.
For these cases, we use extends to force a value to have length:
function getLength<T extends { length: number }>(
value: T,
): number {
return value.length;
}
getLength("TypeScript"); // Valid
getLength([10, 20]); // Valid
getLength(100); // TypeScript error
#The Difference between 'as', 'satisfies' and 'is'
Let's look at them separately.
#as: a type assertion
Let's assume we have a product type:
type Product = {
title: string;
price: number;
inStock: boolean;
};
And some data which we don't know the type of:
const incoming: unknown = {
title: "Keyboard",
price: "100",
inStock: true,
};
As you can see, the price of this unknown type is a string, but the main product type has a number type for the price. To prevent that we can assert that an unknown type is like a product type:
const product = incoming as Product;
Now TypeScript treats product.price as a number. Keep in mind that "as" does not convert the types. It changes how TypeScript views it.
#satisfies: check compatibility while keeping specific information
Like the name, the type you use this for must satisfy the type you are using this for. For example, imagine we define settings for our blog:
type BlogSettings = {
theme: "light" | "dark";
postsPerPage: number;
};
With a normal type annotation:
const settings: BlogSettings = {
theme: "dark",
postsPerPage: 10,
};
The property settings.theme has the declared type "light" | "dark":
const darkTheme: "dark" = settings.theme;
This code will give us errors because the theme setting can be dark or light.
Now we use satisfies:
const settings = {
theme: "dark",
postsPerPage: 10,
} satisfies BlogSettings;
TypeScript now just checks the compatibility with BlogSettings and also catches the invalid values too:
const invalidSettings = {
theme: "blue", // Error
postsPerPage: "ten", // Error
} satisfies BlogSettings;
This concept is usually used for configuration objects where you want compatibility checks without replacing the expression's specific type with a broader annotation.
#is: describe a function that narrows a value
This type will be used in a function's return type. The real world use case is for checking if the data is equal to a type we want and if it is, TS knows it after it checks it too. For example, this function returns a boolean, and after a product has passed, this function knows that the passed value is a product with the same types:
function isProduct(value: unknown): value is Product {
return (
typeof value === "object" &&
value !== null &&
"title" in value &&
typeof value.title === "string" &&
"price" in value &&
typeof value.price === "number" &&
"inStock" in value &&
typeof value.inStock === "boolean"
);
}
#How to choose between them
| Situation | Suitable approach |
|---|---|
| You have extra knowledge about a value’s type | An as assertion, when justified |
| You’re defining settings and want compatibility checks | satisfies |
| You’re inspecting unknown data before using it | Runtime checks, potentially wrapped in an is function |
Related articles
Give AI agents a clear guide to your projects. Learn what to include in AGENTS.md and how to organize your instruction and which common mistakes to avoid.
4 minute read
Read article