1

我不确定为我从后端服务接收的响应对象添加打字稿类型的最佳方法:

{
    de49e137f2423457985ec6794536cd3c: {
        productId: 'de49e137f2423457985ec6794536cd3c',
        title: 'item 1',
    },
    d6623c1a2b843840b14c32685c212395: {
        productId: 'd6623c1a2b843840b14c32685c212395',
        title: 'item 2',
    },
    ids: [
        'de49e137f2423457985ec6794536cd3c',
        'd6623c1a2b843840b14c32685c212395',
    ],
}

它包含一个项目 id 数组string[]以及索引签名[id: string]: Item

Typescript 似乎不喜欢在单个界面中拥有索引签名和数组。例如:

interface ItemList {
    [id: string]: Item;
    ids: string[];
}

我知道在使用索引签名时,其他属性需要返回相同的类型。我是 Typescript 的新手,我有点不确定如何在不将ID从项目对象中移出的情况下使用这些数据?

interface ItemList {
    [id: string]: Item;
    ids: string[];
}
interface Item {
    productId: string;
    title: string;
}

const item: ItemList = {
    de49e137f2423457985ec6794536cd3c: {
        productId: 'de49e137f2423457985ec6794536cd3c',
        title: 'item 1',
    },
    d6623c1a2b843840b14c32685c212395: {
        productId: 'd6623c1a2b843840b14c32685c212395',
        title: 'item 2',
    },
    ids: [
        'de49e137f2423457985ec6794536cd3c',
        'd6623c1a2b843840b14c32685c212395',
    ],
};
console.log(item.ids.map((id: string) => item[id]));

错误

类型“项目”上不存在属性“地图”| 细绳[]'。

“项目”类型上不存在属性“地图”。

4

1 回答 1

2

这里的简单修复是使用交叉类型:

type ItemList = {
    [id: string]: Item;
} & {
    ids: string[];
}
interface Item {
    productId: string;
    title: string;
}

const item: ItemList = Object.assign({ // Can't build the object directly 
    de49e137f2423457985ec6794536cd3c: {
        productId: 'de49e137f2423457985ec6794536cd3c',
        title: 'item 1',
    },
    d6623c1a2b843840b14c32685c212395: {
        productId: 'd6623c1a2b843840b14c32685c212395',
        title: 'item 2',
    }
}, {
    ids: [
        'de49e137f2423457985ec6794536cd3c',
        'd6623c1a2b843840b14c32685c212395',
    ],
});
console.log(item.ids.map((id: string) => item[id]));

交集类型允许不一致的命名属性-索引组合。(请注意,这不是严格类型安全的,因为item['ids']不会Item按预期返回,但对于这种情况,这似乎是一个不错的权衡)

于 2019-06-25T07:55:42.490 回答