Object Types & Enums

Object Types & Enums: An object type is like a shipping manifest contract — it says 'this package must have a recipient name, a tracking code, and a weight,' and if one is missin

An object type is like a shipping manifest contract — it says 'this package must have a recipient name, a tracking code, and a weight,' and if one is missing, the box never leaves the warehouse. So why catch this before runtime, before the package actually ships, instead of after? Because spotting a missing field in the warehouse is far cheaper than discovering it after it reached the customer — Java already enforced this contract with an interface or class; TypeScript adds that same guarantee onto plain JavaScript objects, where it was always optional. The QA-relevant payoff: when a test-result object is missing its `duration` field, plain JavaScript lets that slip through quietly, showing up as 'undefined ms' somewhere in a report; TypeScript code using an object type gets the compiler to call out that same gap before the code is ever committed.

Micro Lab: TypeScript coding practice

Replace the TODO line with the critical line from the expected solution. This is not a real runtime; the goal is to reinforce writing the correct structure in a controlled way.

function foo(obj: { name: string; age: number }) — for small one-off structures

timeout?: number — field may be absent, starts as undefined

readonly id: number — like final in Java, cannot be changed once assigned

Order object type properties by type safety level:

readonly — immutability guaranteed

required field — always present

optional? — may be present or undefined

index signature [key: string] — dynamic

In type Config = { baseUrl: string; timeout?: number }, what happens when object is created without timeout?

Valid — timeout will be undefined (thanks to optional '?')

Compile error — all fields are required