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

如何将对象转换为符合指定interface结构的对象?

解决方案:提取对象指定属性以匹配TypeScript Interface

在TypeScript中,由于Interface仅存在于编译阶段,我们需要在运行时手动提取目标属性,同时保证类型安全。这里有几种实用的实现方式:

1. 手动提取(适合属性较少的场景)

这是最直接的方式,明确指定要保留的属性,TypeScript会自动帮你做类型校验:

// 定义目标Interface
interface TargetInterface {
  bar: number;
  quux: number;
}

// 原始对象
const foo = { bar: 1, baz: 2, quux: 3 };

// 提取符合Interface的属性
const filteredObj: TargetInterface = {
  bar: foo.bar,
  quux: foo.quux
};

// 此时 filteredObj 仅包含 { bar: 1, quux: 3 },完全匹配 TargetInterface

2. 通用工具函数(适合属性较多或需要复用的场景)

如果需要处理多个类似的对象,可以写一个通用的pick函数,结合TypeScript内置的Pick工具类型,既保证类型安全又能复用逻辑:

interface TargetInterface {
  bar: number;
  quux: number;
}

/**
 * 从对象中提取指定属性的通用函数
 * @param obj 原始对象
 * @param keys 需要保留的属性键数组
 * @returns 仅包含指定属性的新对象
 */
function pick<T, K extends keyof T>(obj: T, keys: K[]): Pick<T, K> {
  return keys.reduce((result, key) => {
    result[key] = obj[key];
    return result;
  }, {} as Pick<T, K>);
}

const foo = { bar: 1, baz: 2, quux: 3 };
// 提取指定属性,类型自动匹配 TargetInterface
const filteredObj: TargetInterface = pick(foo, ['bar', 'quux']);

这个pick函数的优势在于:

  • 类型约束:K extends keyof T确保你传入的键一定是原始对象存在的属性,避免拼写错误
  • 精确类型返回:Pick<T, K>让返回的对象类型精确匹配你提取的属性,完美契合目标Interface

注意事项

  • 如果你担心原始对象可能缺少目标属性,可以给Interface的属性加上可选标记(?:),或者在提取时添加默认值
  • 不要依赖TypeScript的类型断言(as TargetInterface)直接转换原始对象,这只会在编译阶段“欺骗”类型检查,运行时对象依然会保留多余属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:02:59