I am trying to replace properties in a typescript type. Observe the following example:
type WithDifferentKeyValue<
T,
K extends keyof T,
R extends { [Key in K]: any },
> = Omit<T, K> & R;
type Child = {
wanted: string;
unwanted: string;
}
type Parent = {
child: Child;
}
type ModifiedChild = Omit<Child, 'unwanted'>
type ModifiedParent = WithDifferentKeyValue<
Parent,
'child',
{ child: ModifiedChild }
>
const invalidModifiedChild: ModifiedChild = {
wanted: "yay i'm wanted!",
unwanted: "oh no I'm not wanted!" // this is correctly marked invalid
}
const invalidModifiedParent1: ModifiedParent = {
child: invalidModifiedChild // for some reason this is considered valid
}
const invalidModifiedParent2: ModifiedParent = {
child: {
wanted: "yay i'm wanted!",
unwanted: "oh no I'm not wanted!" // this is correctly marked invalid
}
}
I have a Parent which I am trying to replace the child key with the modified child. This modified child should have the key wanted key but omit the unwanted key.
WithDifferentKeyValue is my best attempt at creating a "replacement" helper.
For some reason, my ModifiedParent type will correctly identify errors if the child object is in-line, but it will fail to identify errors if the child object is passed in as a variable. Are there any typescript gurus out there that might be able to explain this to me? Or suggest an alternate solution where ModifiedParent will correctly error on even variables passed in for child? Thanks in advance