【发布时间】:2021-04-24 15:52:42
【问题描述】:
TypeScript 版本:^3.5.3
对于这个json
const config = {
id: 1,
title: "A good day",
body: "Very detailed stories"
publishedAt: "2021-01-20 12:21:12"
}
可以改成新标题,展开语法为 as
const newConfig = {
...config,
title: "A new day"
}
最终的newConfig 数据将是
{
id: 1,
title: "A new day",
body: "Very detailed stories"
publishedAt: "2021-01-20 12:21:12"
}
但在这种情况下
const config = {
id: 1,
articleConfig: {
version: "2",
configs: [
{
title: "A good day",
body: "Very detailed stories"
publishedAt: "2021-01-20 12:21:12"
}
]
}
}
还想更改title 的值。试过了
const newConfig = {
...config,
articleConfig: {
configs: [
{
title: "A new day"
}
]
}
它会破坏预定义的 json 架构:
const newConfig: {
id: number;
articleConfig: {
version: string;
configs: {
title: string;
body: string;
publishedAt: string;
}[];
};
}
那么有没有一种简单的方法可以只覆盖这种 json 中的一项?
【问题讨论】:
-
记住 json 是 javascript。并且在 javascript 中对象是可变的。无需使用不可变样式复制使事情复杂化。
-
TypeScript 的版本是
^3.5.3。那么你的意思是如何让一个新的数据库成为当前的数据库呢? -
我想知道为什么一切都是常量。您可以克隆对象并对其进行变异。
标签: javascript json typescript operators spread-syntax