首先,我不确定我的代码出了什么问题,所以如果有更好的标题建议,我会编辑它,谢谢.
我试着用联合类型的"key"来索引一个对象,如果键的类型缩小了,没有问题,但如果类型是联合类型,TS就不满意了,为什么?
我也不理解TS说的错误,那个交叉点类型是从哪里来的?
type FetchedData = {
A?: {
A:'A',
otherField: string
},
B?: {
B:'B',
otherField: string
},
C?: {
C:'C',
otherField: string
},
};
type CachedData = {
A: {
A:'A'
},
B: {
B:'B'
},
C: {
C:'C'
},
};
const cachedData: CachedData = {
A: {
A:'A'
},
B: {
B:'B'
},
C: {
C:'C'
},
}
type Key = keyof FetchedData;
const key: Key = Math.random() > 0.6 ? 'A' : Math.random() > 0.3 ? 'B' : 'C';
const fetchedData: FetchedData = {};
switch (key) {
case "A" : {
const cache = cachedData[key]
fetchedData[key] = {...cache, otherField: 'otherField'}
}
// the above is okay, but te below is not, why?
default : {
const cache = cachedData[key]
/*
const cache: {
A: 'A';
} | {
B: 'B';
} | {
C: 'C';
}
*/
fetchedData[key] = {...cache, otherField: 'otherField'}
/*
Type '{ otherField: string; A: "A"; } | { otherField: string; B: "B"; } | { otherField: string; C: "C"; }' is not assignable to type '({ A: "A"; otherField: string; } & { B: "B"; otherField: string; } & { C: "C"; otherField: string; }) | undefined'.
Type '{ otherField: string; A: "A"; }' is not assignable to type '{ A: "A"; otherField: string; } & { B: "B"; otherField: string; } & { C: "C"; otherField: string; }'.
Property 'B' is missing in type '{ otherField: string; A: "A"; }' but required in type '{ B: "B"; otherField: string; }'.ts(2322)
*/
// I don't understand why TS says "... not assignable to type '({ A: "A"; otherField: string; } & { B: "B"; otherField: string; } & ..." where does that intersection come from?
}
}