实现说明
底层就是函数 headerRow、renderRow。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 文件在加载时定义 headerRow、renderRow。
签名一览:const headerRow = (Object.keys(columns)
核心语句
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]);
});
代码示例
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(" | "));