Playground link. 我有一个有区别的对象类型联合:
export type ADiscriminatedUnion = {
type: 'a',
dataKeyA: number,
anotherDataKeyA: number,
} | {
type: 'b',
dataKeyB: number,
anotherDataKeyB: number,
} | {
type: 'c',
}
type AllTypes = ADiscriminatedUnion['type'];
我创建一个对象,将some种类型(但不是全部)映射到该类型对象中存在的部分属性列表:
const DiscriminatedUnionTypeToListOfDataKeysMap = {
a: ['dataKeyA'],
b: ['dataKeyB', 'anotherDataKeyB'],
} as const satisfies {
[Type in AllTypes]?: Array<
keyof Omit<Extract<ADiscriminatedUnion, { type: Type }>, 'type'>
>;
};
type TypesWhichAreMappedToDataKeys =
keyof typeof DiscriminatedUnionTypeToListOfDataKeysMap;
现在我想创建一个函数,该函数只能接受在第二个代码块的映射中定义的类型对象,并通过列出的属性进行映射.
function doSomethingWithDataKeys(
data: Extract<ADiscriminatedUnion, { type: TypesWhichAreMappedToDataKeys }>
) {
const stringifiedDataKeys = DiscriminatedUnionTypeToListOfDataKeysMap[data.type]
.map(key => `${data[key]}`).join('_');
}
这个错误在data[key]
:
Property 'dataKeyA' does not exist on type '{ type: "a"; dataKeyA: number; anotherDataKeyA: number; } | { type: "b"; dataKeyB: number; anotherDataKeyB: number; }'.
TypScript似乎不会缩小DiscriminatedUnionTypeToListOfDataKeysMap[data.type]
的范围来将结果值(属性名称数组)与传递的对象的属性进行匹配.我如何指示它这样做?