TypeScript中如何定义Nivo柱状图的未知数量记录模式类型?
在TypeScript中定义Nivo柱状图的数据类型
问题描述
我正尝试在TypeScript中使用Nivo柱状图,但不确定如何定义所需的数据类型。我已尝试两种方式:
- 对象索引签名:
{[Key: string]: string;} - Record工具类型:
Record<string, string>
Nivo提供的示例数据如下:
const data = [ { country: 'AD', 'hot dog': 111, 'hot dogColor': 'hsl(168, 70%, 50%)', burger: 19, burgerColor: 'hsl(123, 70%, 50%)', sandwich: 161, sandwichColor: 'hsl(91, 70%, 50%)', kebab: 199, kebabColor: 'hsl(347, 70%, 50%)', fries: 153, friesColor: 'hsl(346, 70%, 50%)', donut: 41, donutColor: 'hsl(96, 70%, 50%)', } ];
我自己尝试的类型定义如下,但存在问题:
export type NivoBarData = { [Key: string]: string; [Key: string]: number; nodeKeyValue?: NivoBarNodeValue; nodeColor?: NivoBarNodeColor; }; export type NivoBarTitle = Record<string, string>; export type NivoBarNodeColor = { [Key: string]: string }; export type NivoBarNodeValue = { [Key: string]: number };
解决方案
你的问题在于重复定义了索引签名,TypeScript不允许一个类型有多个不同类型的索引签名。针对Nivo柱状图的这种数据结构,推荐以下几种定义方式:
方式一:固定字段+联合类型索引签名
适合明确存在固定字段(比如country),同时有动态品类名和对应颜色字段的场景:
// 单条数据类型 export type NivoBarItem = { country: string; // 动态字段支持数值(品类值)或字符串(颜色值) [key: string]: string | number; }; // 数据数组类型 export type NivoBarData = NivoBarItem[];
方式二:泛型约束(精准类型提示)
如果想严格约束品类名和对应颜色字段的命名规则(比如xxx对应xxxColor),可以用泛型实现:
// 定义所有可能的品类名称 type Category = 'hot dog' | 'burger' | 'sandwich' | 'kebab' | 'fries' | 'donut'; // 自动生成对应颜色字段的类型 type CategoryColor = `${Category}Color`; // 单条数据类型:固定country + 所有品类字段 + 对应颜色字段 export type NivoBarItem = { country: string; } & { [K in Category]: number; } & { [K in CategoryColor]: string; }; // 数据数组类型 export type NivoBarData = NivoBarItem[];
这种方式能获得精准的类型提示,避免拼写错误,比如输入hotdog(少空格)时TypeScript会直接报错。
方式三:直接使用Nivo官方类型
Nivo已为柱状图提供了官方类型,可直接导入使用:
import { BarDatum } from '@nivo/bar'; // 直接使用官方定义的类型 export type NivoBarData = BarDatum[]; // 如需扩展字段(比如country),可基于官方类型扩展 export type NivoBarItem = BarDatum & { country: string; }; export type NivoBarData = NivoBarItem[];
内容的提问来源于stack exchange,提问作者GatesKennedy
相关产品推荐
相关产品推荐

