如何创建包含对象数组特定键所有值的TypeScript类型?
问题:如何从数组值中创建限定的字面量类型?
我定义了如下接口:
interface OrderPurchase { headerName: string; minWidth: number; }
还有对应的对象数组:
const columns: OrderPurchase[] = [ { headerName: 'ID', minWidth: 78, }, { headerName: 'Email', minWidth: 250, }, { headerName: 'Name', minWidth: 180, }, { headerName: 'Country', minWidth: 80, }, { headerName: 'Total', minWidth: 80, }];
我想创建一个HeaderName类型,让它只能取数组中headerName的所有值(也就是ID、Email、Name、Country或Total)。但我尝试的代码只把类型限定成了string:
type HeaderName = typeof columns[number]['headerName'];
解决方案
问题出在你手动给columns标注了OrderPurchase[]类型——TypeScript会直接把数组里的headerName值统一推断为string,而不是具体的字面量。要保留这些具体值的类型,得让TypeScript自动推断数组的结构,而不是提前限定死类型。
方法一:使用as const断言 + satisfies校验
直接给数组加上as const断言,让TypeScript把每个元素的属性都推断为字面量类型,同时可以用satisfies确保数组符合OrderPurchase的结构:
interface OrderPurchase { headerName: string; minWidth: number; } const columns = [ { headerName: 'ID', minWidth: 78 }, { headerName: 'Email', minWidth: 250 }, { headerName: 'Name', minWidth: 180 }, { headerName: 'Country', minWidth: 80 }, { headerName: 'Total', minWidth: 80 }, ] as const satisfies readonly OrderPurchase[]; type HeaderName = typeof columns[number]['headerName']; // 此时HeaderName的类型是 "ID" | "Email" | "Name" | "Country" | "Total"
这种方式既能保留字面量类型,又能保证数组结构符合接口要求,不会出现属性缺失或类型错误的情况。
方法二:拆分定义推导类型
如果必须给columns指定OrderPurchase[]类型,可以先定义一个保留字面量的原始数组,再基于它推导类型:
interface OrderPurchase { headerName: string; minWidth: number; } // 先定义字面量数组,让TypeScript推断具体值 const rawColumns = [ { headerName: 'ID', minWidth: 78 }, { headerName: 'Email', minWidth: 250 }, { headerName: 'Name', minWidth: 180 }, { headerName: 'Country', minWidth: 80 }, { headerName: 'Total', minWidth: 80 }, ] as const; // 再把数组转换为OrderPurchase[]类型 const columns: OrderPurchase[] = [...rawColumns]; // 从rawColumns推导HeaderName类型 type HeaderName = typeof rawColumns[number]['headerName'];
内容的提问来源于stack exchange,提问作者Miloš Bošković
相关产品推荐
相关产品推荐

