创建嵌套对象的正确类型注解
在我的项目中,使用Vue,我有一个设备列表,分成一个结构:domain/family/member
为了创建导航结构,我有下面的代码来派生一个保存各个部分的对象:
type Device = { name: string };
type Members = { [key: string]: Device };
type Families = { [key: string]: Members };
type Domains = { [key: string]: Families };
// Order devices into groups to allow for better navigation
const deviceTree: Ref<Domains> = computed(() => {
const tree = devices.value.reduce((acc: Domains, device: string) => {
const parts = device.split('/');
let current = acc;
for (const part of parts.slice(0, -1)) {
current = current[part] = current[part] || {};
// ^^^^^^^ : TS error see below
}
current[parts[parts.length - 1]] = { name: device };
return acc;
}, {});
return tree;
});
这样工作没问题,但TypeScript在 for循环中关于 current 的关联性报错:
Type 'Families' is not assignable to type 'Domains'.
'string' index signatures are incompatible.
Type 'Members' is not assignable to type 'Families'.
'string' index signatures are incompatible.
Type 'Device' is not assignable to type 'Members'.
Property 'name' is incompatible with index signature.
Type 'string' is not assignable to type 'Device'.
这个问题可能是什么原因导致的?
解决方案
经过一些尝试,似乎这就是答案:
type Device = { name: string };
type Members = { [key: string]: Device };
type Families = { [key: string]: Members | {} };
type Domains = { [key: string]: Families | {} };
这使得将families和 domains设置为空对象的逻辑成立。不过也许可以有更简洁的实现。
更新:感谢 @jonrsharpe在下方的评论。对我而言,这个方案更合适:
type Device = { name: string };
type Members = { [key: string]: Device };
type Families = { [key: string]: Members };
type Domains = { [key: string]: Families };
const deviceTree: Ref<Domains> = computed(() => {
const tree = devices.value.reduce((domains: Domains, device: string) => {
const [domain, family, member] = device.split('/');
const families = (domains[domain] = domains[domain] || {});
const members = (families[family] = families[family] || {});
members[member] = { name: device };
return domains;
}, {});
return tree;
});
为了允许设备结构的任意深度而额外添加的循环让事情变得过于复杂。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。