TypeScript and asynchronous values
TypeScript describes expected values during development. For example, a Book type can require a title and a numeric price. Types help detect mistakes in source code, but they are not validation of data arriving from a URL or network. An async function returns a promise; awaiting the promise obtains its settled value or throws its rejection.
Resolve a synthetic book value
type Book = { title: string; price: number };async function readBook(): Promise<Book> { return { title: "Moss", price: 12 };}async function show() { const book = await readBook(); return book.title;}Calling show() produces a promise that fulfills with the string Moss. An async function does not return the string directly. If readBook rejects, the await expression throws inside show and its returned promise rejects unless the failure is handled. This pure example does not need a Next.js server. Later, App Router pages can await data and asynchronous route parameters.
Validate unknown data
A user-controlled object must be checked before being treated as a Book. A type assertion such as value as Book does not examine the runtime value. Check that the input is a non-null object and that the required properties have the expected types; add business constraints such as a nonnegative finite price. For example, reject an array, then check title and price as unknown property values before constructing a new Book object. A blank title or NaN price must not pass merely because its JavaScript type is string or number.
Common mistake
Do not mistake TypeScript success for authorization or runtime validation. A valid number can still be an unauthorized record ID.
Try it yourself
Explain the difference between Promise<Book> and Book, then describe what you would reject in external book input.
Example status: static walkthrough; Next.js build and browser behavior have not been executed in this authoring environment.