Trying to type a curried function which takes a functor first and then an object
type TestType = {
x: number;
y: number;
hello: string;
};
type CordinateType = {
data: TestType;
id: string;
};
const transform = <T extends object, K extends keyof T>(
fntor: (val: T[K]) => any
) => (obj: T) =>
Object.entries(obj).reduce((acc, [k, v]) => ({ ...acc, [k]: fntor(v) }), {});
const testData: CordinateType = {
id: "uuid-222-uuid",
data: {
x: -3,
y: 2,
hello: "test"
}
};
const positive = (x) => (Number.isInteger(x) ? Math.abs(x) : x);
const result = { ...testData, data: transform(positive)(testData) };
console.log("result", result);
Transform is simple function that takes functor and maps over an object.
The main issue is that type of result.data is {}, instead it should be TestType
This is sample react app, the setState hook function is not able to deduce proper type
Update
You can pass one of the generic parameters (
T). Note that a default value needs to be used for the second parameter because we either let typescript figure out the parameters or pass them explicitly.The type of
fntoris incorrect becausevalisn't a key of the object, it's one of the values.Here's the fixed code: