我最近正在将一些旧项目转换为 Typescript,但遇到了一些嵌套对象类型...基本上我有两种基于后端响应对象创建的类型,它们有一些共同点
我最近正在将一些旧项目转换为 Typescript,但遇到了一些嵌套对象类型...基本上,我有两种基于后端响应对象创建的类型,它们具有一些共同的属性,例如, index
但也有一些独特的属性,例如 sharkEnabled
:
type TSharkItem = {
index: string;
sharkEnabled: boolean;
};
type TGrapeItem = {
index: string;
grapeEnabled: boolean;
};
// Union type of data for later use
type TData = TGrapeItem[] | TSharkItem[];
现在我有了映射函数 mapDataToState
,它需要知道 TData
要使用哪种类型并从中创建适当的状态。为此,在字段之间创建了某种“连接器/映射”:
// Connector/mapping
const columnMap = {
fruit: {
enabledColumn: "grapeEnabled",
},
fish: {
enabledColumn: "sharkEnabled",
},
} as const;
type ColumnMap = typeof columnMap;
type AvailableColumnName = ColumnMap["fish"] | ColumnMap["fruit"];
// Return type of mapDataToState fn
type State = { isEnabled: boolean }[];
const mapDataToState = (data: TData, columnNames: AvailableColumnName): State => {
return data.reduce((memo, row) => {
return [
...memo,
{
isEnabled: row[columnNames.enabledColumn], // ERROR: Property 'grapeEnabled' does not exist on type 'TSharkItem | TGrapeItem'.
},
];
}, [] as State);
};
我从 TS 中了解到错误,那肯定 grapeEnabled
只存在于 TGrapeItem
类型中,而不是 TSharkItem
- 但不幸的是,我对 TS 世界还很陌生,我不确定是否有可能实现。
任何提示都非常感谢:)
TS 游乐场链接:
https://www.typescriptlang.org/play/?#code/MYewdgzgLgBKA2BXAtmAsgQwA4wLwwG8AoGGAMwCdEBLKALkJNJgFMwMAjeFgEwGEQSVAwBEAcwrYWAUXZdeIgDRMAvstJlqEABYNizVnO79BKMKJ0YKAa1mdjS1cpuwMEOOGgBuI kSgBPLBYYASF0bDwYAKCQMg8wzCwfaOCAQQA3DGp4exZQswA5DGRg-HzURIBtEU0dEQBdGAAfENMK7GrKGigGnz9A4IAVAGVtK2sASSgWZEj9GGowHhYADwZoCkWxH1 JLGzt5HgYOEEEWDDAfFT6UmEGAcUkgqZm5pkXltZgNrZ2YCSkB2Mx1O3AuVxuAzuABEMFAMJEHk8WC9kJVGi0RmMbKj0ZCgjBhvDpnMFhAgbwQWcLjAVHiiKBILBkNhYfDBiAiXDSjAABQ8OEYBiDNkYRT xQrFFgQBgZLI5eTlMBFEoASgYXJJuAAfIxSBQWFBEBQwDABfCAHQGniIYAsXm8krIEDiiggADuqrwuvm+sNxtNlSYBgtoadLuDzF9BjJFKOMDd7sqCElJQgFrYuRMYXq6hjakj9T+ahg6Nc7k1LFVEKIQA