gpt4 book ai didi

javascript - 是否可能有一个与 API 返回的内容不同的 Typescript 接口(interface)?

转载 作者:行者123 更新时间:2023-11-28 14:27:14 24 4
gpt4 key购买 nike

我想这是一个一般性的编程问题,但对于 AJAX 类型的东西我基本上还是一个初学者。

假设我正在使用一个 API,其中创建者并不关心如何命名(或者至少不关心我这样做的方式),因此响应如下所示:

{
data: [{
sdt: '2018-10-12',
firstnm: 'Stevo',
pos: 'Assistant to the Manager'
}]
}

但我希望我的界面使用驼峰命名约定具有更清晰的名称,如下所示:

export interface IHiringData {
startDate: string,
firstName: string,
position: string
}

这可能吗?或者我是否一直在定义一个模仿 API 返回的接口(interface)?如果我能使用我想要的接口(interface),有什么好的方法可以将返回的数据映射到Typescript接口(interface)?

最佳答案

一种解决方案是简单地将 JSON 数据映射到与您的界面匹配的新对象。

export interface IHiringData {
startDate: string
firstName: string
position: string
}

const json = {
data: [{
sdt: '2018-10-12',
firstnm: 'Stevo',
pos: 'Assistant to the Manager'
}]
}

const hiringData: IHiringData[] = json.data.map(x => ({
startDate: x.sdt,
firstName: x.firstnm,
position: x.pos
}))

关于javascript - 是否可能有一个与 API 返回的内容不同的 Typescript 接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52783463/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com