
本文旨在解决将 JSON 字符串数据转换为 TypeScript 接口数据类型时,如何进行有效的类型转换,特别是将字符串转换为数字类型。我们将探讨使用 JSON.parse 的 reviver 函数进行转换的替代方案,并提供使用 map 函数进行类型转换的示例代码,以及最佳实践建议。
虽然可以使用 JSON.parse 的 reviver 函数进行类型转换,但更清晰、更易于维护的方法是使用 map 函数。这种方法允许您显式地控制每个字段的转换过程,并能更好地处理错误。
以下是一个示例,展示了如何使用 map 函数将包含字符串类型数字的 JSON 数组转换为 TypeScript 接口数组,并进行类型转换:
type Card = {
sub_type: number;
year: number;
peak: string;
}
type SerializedCard = {
sub_type: string;
year: string;
peak: string;
}
function stringToNumberExn(s: string): number {
const n = Number.parseInt(s);
if (Number.isNaN(n)) {
throw new Error(`stringToNumberExn: ${s} is not a number`);
}
return n;
}
async function getCards(): Promise<Array<Card>> {
// 模拟从后端获取的 JSON 数据
const res: Array<SerializedCard> = [
{ sub_type: "0", year: "2023", peak: "N" },
{ sub_type: "1", year: "2024", peak: "Y" }
]; //await fetch("/path/to/cards").then(r => r.json());
// 使用 map 函数进行类型转换
return res.map(card => ({
sub_type: stringToNumberExn(card.sub_type),
year: stringToNumberExn(card.year),
peak: card.peak
}));
}
// 示例调用
getCards().then(cards => console.log(cards));代码解释:
虽然 map 是更推荐的方法,但为了完整性,这里也提供使用 JSON.parse 的 reviver 函数的示例:
本文档主要讲述的是JSON.NET 简单的使用;JSON.NET使用来将.NET中的对象转换为JSON字符串(序列化),或者将JSON字符串转换为.NET中已有类型的对象(反序列化?)。希望本文档会给有需要的朋友带来帮助;感兴趣的朋友可以过来看看
0
type Card = {
sub_type: number;
year: number;
peak: string;
}
const jsonString = `[{"sub_type": "0", "year": "2023", "peak": "N"}, {"sub_type": "1", "year": "2024", "peak": "Y"}]`;
const cards: Card[] = JSON.parse(jsonString, (key, value) => {
if (typeof value === 'string' && !isNaN(Number(value))) {
return Number(value);
}
return value;
});
console.log(cards);代码解释:
注意: 这种方法可能会导致一些问题,例如:
通过遵循这些最佳实践,您可以更有效地将 JSON 数据转换为 TypeScript 接口,并编写更健壮、更易于维护的代码。
以上就是JSON 字符串转 TypeScript 接口:类型转换的实用指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号