Object types#
Write object structures as inline annotations, type aliases, or
interface declarations.
Inline annotation.
const u: {id: string; name: string} = {id: "1", name: "rk"};
type alias.
type User = {id: string; name: string; email?: string};
const u2: User = {id: "1", name: "rk"};
interface declaration; supports declaration merging.
interface User2 {
id: string;
name: string;
email?: string;
}
type aliases work on any type (unions, primitives, tuples,
mapped types); interface is restricted to object structures but
supports declaration merging across files. Modern code uses
type by default; interface when the structure might need
augmentation (e.g. extending Express.Request).
References#
Unions and intersections for
A | BandA & Bover object types.Type operators for
keyof TandT[K].