Partial, Required, Readonly, Pick, Omit
Partial makes all fields optional, Required removes that, Readonly adds readonly, Pick keeps the chosen keys and Omit removes them; all are mapped types. Traps: Omit does not check its key, so a typo removes nothing, and Partial without exactOptionalPropertyTypes allows an explicit undefined, which a spread carries into the result. Readonly and Partial are shallow, and Readonly has no effect at runtime.
TypeScript · Utility types
A data factory takes Partial, a test passes undefined from config, and the request goes out without a currency. Why are types silent?
A test data factory exists in almost every framework: the base object is valid, and a test overrides only what matters for the scenario. The natural parameter type for it is Partial<TransferRequest>. Everything compiles, tests are green, then the request reaches the server without the currency field and the investigation looks like a backend bug. This lesson is about five utilities that build one type from another, how they are made, and where each quietly allows too much.
How it works and why. The utilities are ordinary generic types from the TypeScript standard library, not special magic. All five are built on mapped types (they walk over the keys of keyof T) and exist so a model is not copied. Here is their simplified shape:
type Partial<T> = { [P in keyof T]?: T[P] };
type Required<T> = { [P in keyof T]-?: T[P] };
type Readonly<T> = { readonly [P in keyof T]: T[P] };
type Pick<T, K extends keyof T> = { [P in K]: T[P] };
type Omit<T, K extends keyof any> =
Pick<T, Exclude<keyof T, K>>;
Partial adds ? to every key, Required removes it (-?), Readonly adds readonly. Pick keeps the listed keys, Omit removes them. Note the difference in the constraint: Pick requires K extends keyof T, so a wrong key does not compile, while Omit has keyof any, that is, any key. This is deliberate: Omit has to work even when a key is missing from the type (for example from one member of a union), but the price is no hint about a typo.
One model, several derived types
Example: a factory that quietly lets undefined through. A base model, a factory and a test that takes the currency from an environment variable:
type Currency = 'UAH' | 'USD';
interface TransferRequest {
fromAccount: string;
toAccount: string;
amount: number;
currency: Currency;
description: string;
}
const base: TransferRequest = {
fromAccount: 'UA213223130000026007233566001',
toAccount: 'UA903052992990004149123456789',
amount: 10_000,
currency: 'UAH',
description: 'autotest',
};
function buildTransfer(
overrides: Partial<TransferRequest> = {},
): TransferRequest {
return { ...base, ...overrides };
}
const fromEnv = process.env.TEST_CURRENCY as Currency | undefined;
const transfer = buildTransfer({ currency: fromEnv });
// the type says Currency, the runtime value is undefined
await request.post('/api/transfers', { data: transfer });
Why this passes. In Partial every field looks like currency?: Currency, and without the exactOptionalPropertyTypes option an optional field allows an explicit undefined value. The spread { ...base, ...overrides } takes every own key of the second object, including a key whose value is undefined, and overwrites the base value with it. The types still consider the result a TransferRequest, because the compiler computes a spread of optional properties as "either the override value or the base one". Then JSON.stringify simply drops undefined and the server gets a request without a currency.
There are two fixes, best combined. First: remove the possibility from the type with exactOptionalPropertyTypes; then { currency: undefined } does not compile and the value from process.env has to be narrowed explicitly.
{
"compilerOptions": {
"strict": true,
"exactOptionalPropertyTypes": true
}
}
Second: in the factory itself, drop keys with undefined before merging, to protect against values the types cannot see (for example ones that came through any or from JSON).
const defined = <T extends object>(o: T): T =>
Object.fromEntries(
Object.entries(o).filter(([, v]) => v !== undefined),
) as T;
function buildTransfer(
overrides: Partial<TransferRequest> = {},
): TransferRequest {
return { ...base, ...defined(overrides) };
}
Partial in a factory
{ ...base, ...overrides }
An explicit undefined in the overrides overwrites the base value. The type stays TransferRequest, the request has a hole.
exactOptionalPropertyTypes and defined()
The compiler forbids an explicit undefined, and the factory drops such keys for data the types cannot see.
Pick, Omit and a create body. The server generates id and createdAt itself, so the create body is the model without them, and a short list view is part of it:
interface Account {
id: string;
iban: string;
currency: Currency;
createdAt: string;
}
type CreateAccountBody = Omit<Account, 'id' | 'createdAt'>;
type AccountSummary = Pick<Account, 'id' | 'iban'>;
type A = Omit<Account, 'idd'>; // compiles, nothing is removed
type B = Pick<Account, 'idd'>; // error: no such key
If a new field appears in Account, CreateAccountBody gets it automatically. The second line with Omit shows the price of flexibility: the typo 'idd' removes nothing and the type quietly stays whole. For critical places people write a stricter version of their own (type StrictOmit<T, K extends keyof T> = Omit<T, K>) or simply check the result with a type test.
Limits and alternatives.
Partial,RequiredandReadonlyare shallow: a nested objectpayer: { name, iban }stays whole. To override onlypayer.nameyou need your ownDeepPartialor to override the whole nested object.Readonly<T>acts only in the compiler. At runtime the object can change unless it is frozen withObject.freeze.Omitdoes not distribute over a union:Omit<A | B, 'x'>keeps only the common keys and loses the discriminant. A union needs a distributive variant of your own.- For data with many variants, separate builder methods (
withAmount,inCurrency) are often better thanPartial: they read like a scenario.
Common mistakes.
- Allowing an explicit
undefinedinPartialand merging with a spread: the field disappears from the request with no error. - Treating
Omitas a key check: a typo is not caught. - Expecting
Readonlyto protect at runtime: it is only a hint to the compiler. - Copying a model by hand into several interfaces instead of deriving: half a year later the fields have drifted apart.
Check yourself
buildTransfer({ amount: undefined }) compiles and the server answers 400. What exactly happened, and what changes in the type and in the factory?
Answer
Without exactOptionalPropertyTypes Partial allows an explicit undefined, the spread overwrites the base amount with it, and the field vanishes from the JSON. Turn on exactOptionalPropertyTypes in tsconfig and drop undefined keys in the factory before merging.
Why does Pick<Account, 'idd'> give an error while Omit<Account, 'idd'> does not?
Answer
Pick limits keys to keyof T, Omit accepts any key at all (keyof any). So an Omit with a typo removes nothing and does not complain.
Partial makes all fields optional, Pick keeps chosen ones, Omit removes them. I use Partial in test data factories so a test overrides only the needed fields. Middle/Senior: They are all mapped types, and they have traps: Omit does not check the key, Partial allows an explicit undefined that a spread carries into the result, and Readonly is shallow and absent at runtime. So I turn on exactOptionalPropertyTypes and drop undefined keys in the factory.