Repeated similar type declarations in TypeScript invite a way to calculate an output type from an input type. What matters is whether readers understand the relationship between types, more than the number of characters saved. Using an imaginary delivery-notification service, this article examines conditional types and infer, distinguishing them from checking whether external data is actually valid.
1. Conditional types branch on a type input
The official conditional-type documentation explains selecting an output type according to an extends condition. This example produces a boolean literal type depending on whether the input is a string type. It is not a function that checks strings at runtime.
type IsText<T> = T extends string ? true : false;
type NameIsText = IsText<'parcel'>; // true
type CountIsText = IsText<3>; // false
Suppose the function creating delivery notifications receives string IDs, while an internal processing function receives numeric IDs. Before using conditional types, be able to explain why these identifiers differ. Separate names help if their meanings really differ; if only their notation differs, unifying the input format may be easier to read. Do not hide unclear data design behind type techniques.
Review expected inputs and outputs as pairs. Small examples for strings, numbers, unions and unexpected inputs reduce the effort of reading complex declarations. Check that results written in comments match the types inferred by the editor. A natural-sounding type name may still compute a different result.
2. Union distribution changes an array’s meaning
When a type parameter appears directly on the left of the condition, distribution applies the condition to every union member. To prevent this and treat the whole union as one, compare a form wrapped in square brackets.
type SeparateLists<T> = T extends unknown ? T[] : never;
type Together<T> = [T] extends [unknown] ? T[] : never;
type A = SeparateLists<string | number>; // string[] | number[]
type B = Together<string | number>; // (string | number)[]
const a: A = ['a', 'b'];
const b: B = ['a', 1];
The first result is an array containing only strings or an array containing only numbers. The second can contain strings and numbers together within one array. The suitable result depends on whether an entire delivery list must contain one code type or each item may use a different type. Both show brackets on screen, but the arrays’ contracts differ.
When debugging, try individual input members rather than reading an entire complicated utility type at once. Compare the results for a string, a number and their union. Establishing whether distribution was intended also explains why brackets may be needed. Record example permitted values as well as the final type result.
3. infer names a type extracted from a structure
In a conditional type, infer names part of the matched structure. The following small type unwraps one level of Promise.
type OneResult<T> = T extends Promise<infer Value> ? Value : T;
type Parcel = OneResult<Promise<{ tracking: string }>>;
type ParcelList = OneResult<Promise<string[]>>;
This code neither runs nor awaits asynchronous work. It expresses the result’s shape at compile time. A function name such as Resolved might suggest an actual value has already arrived, so consider where this type is used and its context. Runtime waiting still belongs in asynchronous code.
If you need a recursively awaited result type, check the standard utility type Awaited before extending the one-level teaching example. Simplicity in an educational type differs from requirements for a shared tool. When introducing a utility to a team, document inputs whose results differ from the standard type and why those differences are needed.
4. Build event names with template literals
Template literal types represent combinations of string literals as types. A delivery service can illustrate event names combining a scope and action.
type Scope = 'parcel' | 'address';
type Action = 'created' | 'updated';
type EventName = `${Scope}:${Action}`;
const event: EventName = 'parcel:created';
The compiler can catch misspelled names, but whether every possible combination is valid in the real service is another matter. For example, if only an address-deletion event is supported, a simple product of scopes and actions may not express the rules accurately. First consider explicitly mapping allowed events to their payloads.
As events multiply, readers must still find the actual names easily. Instead of chaining many automatic combination rules, you might keep names sent to external systems visible in one file. Compare how a new teammate would discover an incorrect event before and after abstraction. Assess sophistication and usability together.
5. Inspect external JSON at runtime
Attaching a type such as User or Parcel to an API response does not guarantee the actual response has that structure. Here is a simple pattern receiving an external value as unknown and checking required fields.
function hasTracking(value: unknown): value is { tracking: string } {
return typeof value === 'object' && value !== null
&& 'tracking' in value && typeof value.tracking === 'string';
}
const incoming: unknown = { tracking: 'DEMO-001' };
if (hasTracking(incoming)) console.log(incoming.tracking);
This check establishes only that tracking is a string. It does not verify whether that tracking number exists or whether the user may view that delivery. Treat narrowing, business rules and authorization as separate responsibilities. The official Narrowing documentation explains how conditions refine type information.
6. A short review sequence for choosing type tools
First write two real values to allow and two to reject. Then express the meaning with ordinary unions and explicit object declarations. Use conditional types or infer when repeated relationships remain; this makes the technique’s purpose clear. If declarations take much longer to read, extracting only the shared portion and keeping the rest as ordinary types is also an option.
Finally, run type checks and runtime checks separately. Checking that the compiler rejects an invalid event name complements checking that the program explains errors when the server omits a field. Verify small examples, then connect them to actual input boundaries so type transformations contribute to safe application design.