Typed Table Column Definitions
Type column definitions against the row's own keys so unknown keys fail compilation and each format callback gets the fully typed row.
Code
interface Invoice {
readonly id: string;
readonly cents: number;
readonly issued: string;
}
// Column definitions keyed by the row's own keys: an unknown key is a
// compile error, and each format receives the fully typed row
type Columns<T> = {
[K in keyof T]?: { readonly header: string; readonly format?: (row: T) => string };
};
const columns: Columns<Invoice> = {
id: { header: "Invoice" },
cents: { header: "Total", format: (row) => `$${(row.cents / 100).toFixed(2)}` },
issued: { header: "Issued" },
};
function renderRow(row: Invoice, columns: Columns<Invoice>): string[] {
return (Object.keys(columns) as (keyof Invoice)[]).map((key) => {
const def = columns[key];
return def?.format ? def.format(row) : String(row[key]);
});
}
const invoice: Invoice = { id: "INV-42", cents: 4950, issued: "2026-11-21" };
const headerRow = (Object.keys(columns) as (keyof Invoice)[]).map((key) => columns[key]?.header ?? key);
console.log(headerRow.join(" | "));
console.log(renderRow(invoice, columns).join(" | "));Output
Captured from a sandboxed run of this snippet in the build pipeline.
Invoice | Total | Issued
INV-42 | $49.50 | 2026-11-21What this snippet does
In short, this is the functions headerRow and renderRow, doing all the work.
What to watch for
- No external surface — behavior comes only from the standard library.
Applying it
Entry signature: const headerRow = (Object.keys(columns)
Statements that matter
const headerRow = (Object.keys(columns) as (keyof Invoice)[]).map((key) => columns[key]?.header ?? key);
[K in keyof T]?: { readonly header: string; readonly format?: (row: T) => string };
return (Object.keys(columns) as (keyof Invoice)[]).map((key) => {
const def = columns[key];
return def?.format ? def.format(row) : String(row[key]);
});
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `headerRow`, `renderRow` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.