I dont understand why the code behaves differently when using generics.
The topic is based on the answer for
How to create a relation between parameters of a function?
interface Data {
a: number,
b: { x: number, y: number}
}
type GetKeyValueTuples<T> = { [Key in keyof T]: [Key, T[Key]] }[keyof T];
function getChangedDataByProperty<T extends Data>(
...[data, changedProp, newPropValue]: [T, ...GetKeyValueTuples<T>]
) {
if (changedProp === "b") {
changedProp
return {
...data,
b: {
// why this has number, a, b types?
x: newPropValue.x,
y: newPropValue.y,
}
}
} else {
return {
...data,
x: newPropValue
}
}
}
// why this behaves differently than the abvove function?
function getChangedDataByProperty2(
...[data, changedProp, newPropValue]: [Data, ...GetKeyValueTuples<Data>]
) {
if (changedProp === "b") {
changedProp
return {
...data,
b: {
x: newPropValue.x,
y: newPropValue.y,
}
}
} else {
return {
...data,
x: newPropValue
}
}
}