【发布时间】: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;
我想避免将对象提取到接口中,因为对象有很多道具,我不想在实现中重复所有道具。
有什么建议吗?
【问题讨论】:
-
定义一个具有可选的、适当类型的属性 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