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

在TypeScript中能否用Interface/Type校验CSV输入数据合法性?

问题:TypeScript中如何用Interface校验CSV读取的资源记录?

我需要从CSV文件中读取包含三个字段的文本数据:

  • AWS资源名称(可为任意ARN)
  • AWS资源类型(仅限"load_balancer"、"ecs_cluster"或"lambda_function")
  • 操作(仅限REMOVE或ADD)

CSV中的每一行称为一个ResourceEntry,我是TypeScript新手,不确定术语是否准确。读取CSV记录时,我希望拒绝无效记录(例如未知操作、未列出的资源类型)。请问能否通过定义ResourceEntry的Interface来实现这一需求?

我当前的代码实现如下:

// 还有一个'class IterableResourceEntry implements ResourceEntry {'
interface ResourceEntry {
  resource_name: string;
  resource_type: ResourceType;
  action: ActionType;
}

interface ActionType {
  type: 'REMOVE' | 'ADD';
}

interface ResourceType {
  type: 'load_balancer' | 'ecs_cluster' | 'lambda_function';
}

是否可以用这些定义来校验每条记录?


回答

你的当前定义存在问题:ActionType和ResourceType是嵌套了type属性的接口,但CSV解析出的原始数据应该是直接的字符串值(比如action字段是"REMOVE"而非{type: "REMOVE"}),所以接口结构和实际数据不匹配,无法直接用于校验。

正确的类型定义方式

应该用字符串字面量类型替代嵌套接口,让ResourceEntry的字段直接对应CSV的原始数据结构:

// 用字面量类型定义合法的枚举值
type ActionType = 'REMOVE' | 'ADD';
type ResourceType = 'load_balancer' | 'ecs_cluster' | 'lambda_function';

interface ResourceEntry {
  resource_name: string;
  resource_type: ResourceType;
  action: ActionType;
}

注意:TypeScript类型是编译时校验,需配合运行时校验函数

TypeScript的接口和类型仅在编译时生效,无法直接验证运行时从CSV读取的原始数据(比如解析后的普通JS对象)。你需要写一个校验函数,把原始数据和类型定义做匹配,过滤无效记录:

function isValidResourceEntry(entry: unknown): entry is ResourceEntry {
  // 先判断是否为合法对象
  if (typeof entry !== 'object' || entry === null) {
    return false;
  }
  // 解构字段并断言类型(后续会做实际校验)
  const { resource_name, resource_type, action } = entry as ResourceEntry;

  // 校验资源名称是字符串
  if (typeof resource_name !== 'string') {
    return false;
  }
  // 校验资源类型是否在合法列表内
  const validResourceTypes: ResourceType[] = ['load_balancer', 'ecs_cluster', 'lambda_function'];
  if (!validResourceTypes.includes(resource_type as ResourceType)) {
    return false;
  }
  // 校验操作类型是否合法
  const validActions: ActionType[] = ['REMOVE', 'ADD'];
  if (!validActions.includes(action as ActionType)) {
    return false;
  }

  return true;
}

使用方式

当你从CSV解析出一行数据后,调用这个函数做校验:

// 假设csvRow是从CSV解析出的原始对象
const csvRow = { resource_name: 'arn:aws:elb:xxx', resource_type: 'load_balancer', action: 'ADD' };

if (isValidResourceEntry(csvRow)) {
  // 这里csvRow会被TypeScript推断为ResourceEntry类型,可以安全使用
  console.log(csvRow.resource_type, csvRow.action);
} else {
  console.log('无效的资源记录');
}

总结:接口(配合字面量类型)可以清晰定义数据的合法结构和值范围,但必须结合运行时校验函数,才能实际过滤CSV中的无效记录。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 15:22:34