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

如何筛选TypeScript中Todo类型对象的指定字段

筛选API返回对象的指定字段

要从API返回的对象中仅保留指定字段,TypeScript的类型定义只是编译时的约束,不会在运行时过滤实际字段,所以需要手动提取需要的属性,以下是几种实现方式:

直接解构提取(简单场景)

修改你的fetchData函数,通过对象解构获取目标字段,再返回新对象,同时修正返回类型避免any:

import axios, { AxiosResponse } from 'axios';

type Todo = {
    id: string;
    title: string;
};

const url = 'https://jsonplaceholder.typicode.com/todos/1';

const fetchData = async (): Promise<Todo> => {
    const response: AxiosResponse = await axios.get(url);
    // 解构提取需要的字段,忽略其他属性
    const { id, title } = response.data;
    // 注意:jsonplaceholder返回的id是数字类型,这里转成字符串匹配Todo类型定义
    return { id: String(id), title };
};

fetchData().then((r) => {
  console.log(r); // 仅输出 { id: "1", title: "delectus aut autem" }
});

通用筛选函数(复用场景)

如果需要多次筛选不同对象的字段,可以封装一个通用的pick函数,灵活提取指定属性:

import axios, { AxiosResponse } from 'axios';

type Todo = {
    id: string;
    title: string;
};

// 通用pick函数:从对象中提取指定键的属性
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 url = 'https://jsonplaceholder.typicode.com/todos/1';

const fetchData = async (): Promise<Todo> => {
    const response: AxiosResponse = await axios.get(url);
    // 使用pick函数提取id和title,转换id类型匹配定义
    const picked = pick(response.data, ['id', 'title']);
    return { id: String(picked.id), title: picked.title };
};

fetchData().then((r) => {
  console.log(r);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 09:37:04