Within this code snippet, the goal is to create a new type from an existing one by iterating through the keys and only replacing those that meet a specific condition.
Additionally, union types are being utilized here.
class A {}
class B {
constructor(public a: A, public n: number, public aa: A[]) {}
}
type X = A | B
type ReplaceKeyTypes<Type extends X, NewKeyType> = {
[Key in keyof Type]: Key extends X ? NewKeyType : Type[Key]
}
const a: A = new A()
const b: B = new B(a, 1, [a, a])
const c: ReplaceKeyTypes<B, string> = {
a: 'test',
n: 2,
aa: ['xyz']
}
In the final lines of the code above, two errors occur:
- The assignment of 'number' to 'string' is invalid.
- The assignment of 'string[]' to 'string' is invalid.
The questions raised include:
- Why does
c.n
switch to a string even though its initial key type is a number, which doesn't fulfill "Key extends X
"? - How can changes be applied to keys that are arrays of the union type as well? For instance, how should
c.aa
shift fromX[]
tostring[]
in this scenario?