【发布时间】:2019-05-27 17:27:35
【问题描述】:
我想优雅地复制一个打字稿结构interfaceName(满足某个接口)。此 TypeScript 包含类型为 Map<IKey, number> 的映射 attribute3,可能需要修改(取决于条件):必须插入额外的键值对。
IKey 同样是一个接口。
interface InterfaceName{
attribute1: string
attribute2: string
attribute3: Map<IKey, number>
}
interface IKey{
a1: number
a2: number
}
}
我的尝试如下:我只是使用... 语法复制interfaceName 的所有成员,然后尝试为attribute3 分配修改后的副本。
但不知何故,这不起作用:最后,无论布尔值如何,相同的 Map 对象都会从函数中传递出去。
const createModifiedCopyIfWished = (interfaceName: InterfaceName, wished: Boolean) => wished ? {
...interfaceName,
attribute3: interfaceName.attribute3.set({a1:1,a2:2},5)
}
:
interfaceName
let a: InterfaceName = {
attribute1: "a",
attribute2: "b",
attribute3: new Map<IKey, number>()
}
let b = createModifiedCopyIfWished(a, true)
// {"attribute1":"a","attribute2":"b","attribute3":{}}
console.log(JSON.stringify(b))
探测方法是什么? 甚至可以在一个语句中实现吗?
工作示例:LiveCode
【问题讨论】:
-
当你说“不知何故这不起作用”时,你是什么意思?两个
InterfaceName对象共享一个共同的Map实例并且您希望它们是不同的实例?这里发生了很多事情可能会给您带来麻烦(例如,您的IKey不是一个很好的密钥类型)并且很难与无法编译的代码(什么是{1,2})分开并且没有除了“不起作用”之外的问题描述。请尝试将其编辑为minimal reproducible example,以便有人可以帮助您。干杯! -
感谢您的反馈。我更正了代码并清楚地指定了不工作的东西。我看到 IKey 不是一个很好的键类型(因为它可以有更多的属性来生成不同的键),因此,我会考虑将它作为一个类。