【问题标题】:Typescript: best way to construct an object that reference itself打字稿:构造引用自身的对象的最佳方法
【发布时间】:2020-03-18 19:59:12
【问题描述】:

我正在尝试将这个简化的 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

【问题讨论】:

  • 定义一个具有可选的、适当类型的属性 a 和 b 的接口,并声明 Test 是该接口的实现。
  • 这将导致大量的代码重复,我在对象上有很多道具。我将编辑我的问题。
  • 哪个对象引用了自己?您能否帮助澄清这个问题的标题,目前是“Typescript:构造引用自身的对象的最佳方法”?现在,该对象不引用自身。它有一个值为{someProp:true}a 属性和一个值为{someProp:true; otherProp: true}b 属性。对象在任何地方都不会引用自己。你能澄清一下你需要什么吗?
  • 如果您的目标不是输入它,而只是让它编译,请将其输入为any
  • Test 定义为{ a: someType; b: someOtherType; }someType 定义为{ someProp: boolean; }someOtherType 定义为extends someType { otherProp: boolean; } typescriptlang.org/play/index.html#code/…

标签: typescript object self-reference


【解决方案1】:

当你重新安排一些东西时,结果应该仍然可以正确推断出来。

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

const test = {a, b}

export default test;

构建这样一个对象的“诀窍”是您需要一次构建它,而不是通过多个步骤修改它。通过颠倒顺序,您可以实现这一目标。

【讨论】:

  • 这个解决方案的问题在于,在我的真实应用程序中,Test 是一个巨大的对象(它是一个包含排版值到键的映射的对象)。这个解决方案会非常臃肿,而打字稿看起来可能会以某种方式自动推断出对象类型。
猜你喜欢
  • 1970-01-01
  • 2017-12-26
  • 2018-06-26
  • 1970-01-01
  • 2019-08-16
  • 2012-12-08
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
相关资源
最近更新 更多