Typescript:构造引用自身的对象的最佳方法

问题描述 投票:0回答:1

我正在尝试将此简化的js代码迁移到ts:

let Test = {};
Test.a = { //error: prop a does not exist
    someProp: true
};

Test.b = {
    ...Test.a,//self referencing
    otherProp: true
};

export default Test;

我想避免将对象提取到接口中,因为该对象具有许多道具,并且我不想在实现中重复所有道具。

有什么建议吗?

Playground Link

typescript object self-reference
1个回答
1
投票

当您重新安排内容时,仍应正确推断结果。

const a = {
    someProp: true
}
const b = {
    ...a,
    otherProp: true
}

const test = {a, b}

export default test;

构建这样的对象的“诀窍”是,您需要一次构建所有对象,而不是分多个步骤对其进行修改。通过颠倒顺序可以实现这一点。

© www.soinside.com 2019 - 2024. All rights reserved.