← 中文资源

简体中文版本

以行类型为键的表格列定义

列定义直接以行的键作为映射键:写错字段名是编译错误,format 回调拿到完整类型的行;渲染时按列顺序输出表头与单元格。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

Invoice | Total | Issued
INV-42 | $49.50 | 2026-11-21

实现说明

底层就是函数 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(" | "));