Spreading with Optional Properties
You'll learn how optional properties behave when spread into new objects and whether they remain optional or become required in the resulting type.
How Spreads Interact with Optional Properties
When you spread an object that has optional properties, TypeScript needs to decide: does the resulting type keep those properties optional, or does it treat them differently?
The key insight: spreading doesn't automatically make optional properties required. If the source object has an optional property, the spread result preserves that optionality:
type Config = {
host: string;
port?: number;
};
const baseConfig: Config = { host: "localhost" };
const newConfig = { ...baseConfig, timeout: 5000 };
// newConfig type: { host: string; port?: number; timeout: number }
Notice port remains optional in newConfig even though we're creating a "new" object literal.
When Optional Properties Become Present
If you spread an object where the optional property is actually present, that specific value carries over, but the type still reflects the optionality:
const fullConfig: Config = { host: "localhost", port: 3000 };
const spread = { ...fullConfig };
// spread type: { host: string; port?: number }
// spread.port is 3000 at runtime, but type still says "might be undefined"
Overriding Optional Properties
When you override an optional property during a spread, the new property can change the optionality:
const withPort = { ...baseConfig, port: 8080 };
// withPort type: { host: string; port: number }
// Now port is required because we explicitly provided it
Key Takeaway: Spreading preserves the optional nature of properties from the source type, but explicitly providing a property in the spread makes it required in the result type.