Below is the code snippet that I am working with:
interface Data {
A: {
a1: string;
a2: string;
};
B: {
b1: number;
b2: string;
};
}
type TransformDataKey<V extends string, T extends string> = `--${V}-${T}`;
type TransformData<
V extends string,
K extends keyof Data,
D = Data[K]
> = {
[k in TransformDataKey<V, keyof D>]: string | number; // <-- error on "keyof D"
};
type K = TransformData<'abc', 'A'>; // <-- this is correct
Upon trying to access keyof D
in the specified line, an error occurs:
Type 'keyof D' does not satisfy the constraint 'string'. Type 'string | number | symbol' is not assignable to type 'string'. Type 'number' is not assignable to type 'string'.ts(2344)
This error arises because keyof D
resolves to never
since A
and B
do not have any common fields. But why is it resolving to string | number | symbol
when none of the keys are numbers or symbols?
On the other hand, the type K
successfully resolves to:
type K = {
--abc-a1: string | number;
--abc-a2: string | number;
}
Is there a correct way to achieve this kind of mapping?