You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript泛型结合特定值实现多语言CSV列映射

解决方案:基于泛型固定语言字段,动态设置列位置

1. 先明确基础类型定义

假设你已有的基础接口如下(若与实际不符,可对应调整):

// 列结构基础接口
interface foodFileStructure<T extends string> {
  colName: T;
  colType: 'string' | 'number' | 'boolean';
  colPos: number;
}

// 通用商品类型
type FoodsoftArticleGeneric<Fields extends Record<string, foodFileStructure<any>>> = Fields;

2. 定义固定语言字段的基础配置

先把德语、英语对应的colName和colType固定为类型常量:

// 德语字段固定配置(仅含colName、colType)
type GermanArticleBase = {
  note: { colName: 'Notiz'; colType: 'string' };
  productName: { colName: 'Produktname'; colType: 'string' };
  price: { colName: 'Preis'; colType: 'number' };
  // 按需添加其他固定字段
};

// 英语字段固定配置(仅含colName、colType)
type EnglishArticleBase = {
  note: { colName: 'Note'; colType: 'string' };
  productName: { colName: 'ProductName'; colType: 'string' };
  price: { colName: 'Price'; colType: 'number' };
  // 按需添加其他固定字段
};

3. 生成动态列位置的泛型类型

创建一个泛型工具,将固定字段配置与动态传入的colPos合并,生成符合FoodsoftArticleGeneric的类型:

// 泛型工具:合并固定字段与动态列位置
type FoodsoftArticleLang<
  Base extends Record<string, { colName: string; colType: 'string' | 'number' | 'boolean' }>,
  PosConfig extends Record<keyof Base, number>
> = FoodsoftArticleGeneric<{
  [K in keyof Base]: foodFileStructure<Base[K]['colName']> & {
    colType: Base[K]['colType'];
    colPos: PosConfig[K];
  };
}>;

4. 定义德语/英语专属类型

基于上面的泛型工具,直接封装出德语和英语的商品类型,仅需在实例化时传入colPos配置:

// 德语商品类型:仅需动态指定colPos
type FoodsoftArticleGerman<PosConfig extends Record<keyof GermanArticleBase, number>> = FoodsoftArticleLang<GermanArticleBase, PosConfig>;

// 英语商品类型:仅需动态指定colPos
type FoodsoftArticleEnglish<PosConfig extends Record<keyof EnglishArticleBase, number>> = FoodsoftArticleLang<EnglishArticleBase, PosConfig>;

5. 实例化使用

实例化时只需传入列位置配置,colName和colType会被自动固定(写错会触发TypeScript类型报错):

// 德语实例:Notiz在第3列,Produktname在第1列,Preis在第2列
const germanItem: FoodsoftArticleGerman<{ note: 3; productName: 1; price: 2 }> = {
  note: { colName: 'Notiz', colType: 'string', colPos: 3 },
  productName: { colName: 'Produktname', colType: 'string', colPos: 1 },
  price: { colName: 'Preis', colType: 'number', colPos: 2 },
};

// 英语实例:Note在第4列,ProductName在第1列,Price在第3列
const englishItem: FoodsoftArticleEnglish<{ note: 4; productName: 1; price: 3 }> = {
  note: { colName: 'Note', colType: 'string', colPos: 4 },
  productName: { colName: 'ProductName', colType: 'string', colPos: 1 },
  price: { colName: 'Price', colType: 'number', colPos: 3 },
};

内容的提问来源于stack exchange,提问作者LeO

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:15:36