TypeScript Essentials
Learn to model data, narrow union types and validate unknown input with a practical TypeScript example.
On this page
TypeScript Essentials
TypeScript checks the assumptions your JavaScript code makes about data. In this guide, we model a library article, format its publication state and validate a field received as external input.
Model a value and let TypeScript infer the rest
type Status = "draft" | "published";
type Article = {
title: string;
status: Status;
tags?: string[];
};
const article: Article = {
title: "TypeScript Essentials",
status: "draft",
};
const tags = article.tags ?? [];The explicit Article annotation checks the object against the contract. The compiler infers that tags is a string[] because the nullish coalescing operator supplies an empty array when the optional property is absent. Use explicit types where they communicate a contract and inference where the value already makes the type clear.
Narrow a union before using its members
A discriminated union describes the fields available in each state. Here, only a published article has a publication date.
type Publication =
| { status: "draft" }
| { status: "published"; publishedAt: string };
function publicationLabel(publication: Publication): string {
if (publication.status === "published") {
return `Published on ${publication.publishedAt}`;
}
return "Draft";
}Checking status narrows publication to the matching branch. The compiler can then verify access to publishedAt.
Validate input at runtime
Types are erased when TypeScript emits JavaScript. A network response or a parsed JSON value may contain unexpected data, even if a type annotation says otherwise. Receive the value as unknown and check it before using it.
function parseStatus(value: unknown): Status {
if (value === "draft" || value === "published") {
return value;
}
throw new Error("Invalid publication status");
}For a complete response object, validate its shape and each required field at the boundary. The rest of the application can work with the validated result.
Try it
Call publicationLabel with a draft and then with a published article that includes a date. Remove the date from the second call and observe the compiler error. Then call parseStatus("archived") to see how the runtime check handles an unsupported value.