Object Types
Describe the shape of an object with inline type annotations.
Syntax
let user: { name: string; age: number };You can describe an object's shape directly in an annotation by listing each property and its type inside curly braces.
Reading the shape
{ name: string; age: number } means the object must have a name that is a string and an age that is a number. Missing or extra properties cause errors.
Example
Loading editor…
Press Run to execute the code.
When to use it
- A function that creates a new post accepts an inline object type so callers must supply exactly the required fields.
- A settings object is typed inline to prevent extra keys from being added by different parts of the codebase.
- A one-off utility function uses an inline shape annotation instead of a named interface to keep the code local.
More examples
Inline object type annotation
Uses an inline object type on a function parameter, requiring both x and y to be present and typed as numbers.
function printCoord(point: { x: number; y: number }): void {
console.log(`x=${point.x}, y=${point.y}`);
}
printCoord({ x: 3, y: 7 });
printCoord({ x: 1 }); // Error: Property 'y' is missingObject type variable
Declares a variable with a full inline object type, ensuring each property maintains its assigned type.
let config: { host: string; port: number; tls: boolean } = {
host: 'localhost',
port: 5432,
tls: false,
};
config.port = '5432'; // Error: Type 'string' is not assignable to type 'number'Nested object types
Nests a named type inside an inline object type to model a structured data shape with multiple levels.
type Address = { street: string; city: string; zip: string };
function formatAddress(addr: { name: string; address: Address }): string {
return `${addr.name}, ${addr.address.city} ${addr.address.zip}`;
}
Discussion