Partial, Required, Readonly
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];
};Rewrite the properties of T as optional, required, or readonly. All three are compile-time mapped types; none of them mutate or freeze a value at runtime.
| Type parameter | Description |
|---|---|
T | An object type whose keys will be mapped. Arrays, functions, and primitives are not the usual input; passing them does not produce a useful field-by-field transformation. |
Produces: A new object type. The original type T is not changed. These aliases do not return a runtime function or a copy of an object.
Type errors
type error— Assigning a Partial nested object is an error when the nested type still requires its own fields. Omitting a property from Required<T> is an error. Assigning to a readonly property is an error at compile time only.
- The signatures above are the declarations from TypeScript 5.9.3's lib.es5.d.ts.
- user.name = "Grace" is rejected by tsc, but the assignment is still present in the emitted JavaScript. Object.isFrozen(user) is false.
- user.profile.city = "Lyon" type-checks because Readonly did not mark the nested city field as readonly.
- These types do not validate JSON or any other runtime input. For that, use a type guard, as in the overview recipe on parsed JSON.
type User = {
name: string;
age?: number;
profile: { city: string };
};
const empty: Partial<User> = {};
const named: Partial<User> = { name: "Ada" };
// @ts-expect-error Partial is shallow, so profile.city is still required
const nested: Partial<User> = { profile: {} };
const requiredUser: Required<User> = {
name: "Ada",
age: 36,
profile: { city: "Paris" },
};
// @ts-expect-error Required makes the optional age property mandatory
const missingAge: Required<User> = {
name: "Ada",
profile: { city: "Paris" },
};
type MaybeName = { name: string | undefined };
const stillUndefined: Required<MaybeName> = { name: undefined };
const user: Readonly<User> = {
name: "Ada",
age: 36,
profile: { city: "Paris" },
};
// @ts-expect-error Readonly only applies to the top-level properties
user.name = "Grace";
user.profile.city = "Lyon";
console.log(named.name, stillUndefined.name, user.name, user.profile.city, Object.isFrozen(user));Expected output
Ada undefined Grace Lyon falseRelated: Validate parsed JSON at runtime, Official Partial, Official Required, Official Readonly, Mapped types