TypeScript Object Types
TypeScript Object Types: Shapes, Optional Keys, and Record
TypeScript object types describe the exact property names and value types an object must carry. You can write object types inline for one-off parameters or extract them into reusable type and interface definitions.
TypeScript uses structural typing ("duck typing"): any object that has the required properties with matching types satisfies the contract, even if it was not declared with that type name.
Optional (?), readonly, and Record Properties
Add ? after a property name to mark it optional, add readonly to prevent reassignment after creation, and use Record<K, V> for dynamic key-value maps.
function printUser(user: {
readonly id: number;
name: string;
nickname?: string;
}): void {
const display = user.nickname ?? user.name;
console.log(`#${user.id}: ${display}`);
}
const featureFlags: Record<string, boolean> = {
darkMode: true,
betaEditor: false,
};
printUser({ id: 7, name: "Nadia" });
console.log(featureFlags.darkMode);
Excess Property Checks on Object Literals
When you pass an object literal directly into a function or typed variable, TypeScript rejects unknown extra properties to catch typos like { nmae: "Nadia" }.
Common Mistakes to Avoid
- Using lowercase
objector{}as a type:{}accepts almost every non-null value (even numbers and strings!), andobjectblocks reading any properties; always specify exact fields orRecord<string, unknown>. - Reading optional fields without checking
undefined: With"strictNullChecks": true,user.nickname.toUpperCase()errors unless you guard with?.or??. - Mutating
readonlyproperties via aliases:readonlystops reassignment on that type view, though another non-readonly reference could still mutate it.
Frequently Asked Questions
What is the difference between Record<string, number> and { [key: string]: number }?
They behave identically in most cases. Record<K, V> is shorter and also accepts union keys like Record<"dev" | "prod", string>, which index signatures cannot express directly.
Can an optional property accept undefined explicitly?
By default nickname?: string means string | undefined. If "exactOptionalPropertyTypes": true is enabled, { nickname: undefined } is disallowed unless written string | undefined.
How do I make all properties of an object optional or readonly?
Use built-in utility types Partial<T> or Readonly<T> instead of duplicating the type definition.
Unlock Your
Full Potential.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Try it Yourself
Experiment with the code from this lesson in our interactive playground.