I have a function, that takes among other things an object of functions:
type ForMembers<S> = {
[Key: string]: (arg: S) => void;
};
export default function transform<S extends { [index: string]: any }, D extends { [index: string]: any }>(
source: S,
interfaceName: string,
forMembers?: ForMembers<S>
): D {
const newObj = extract(source, getKeys(interfaceName));
if (forMembers) {
Object.keys(forMembers).forEach((key) => forMembers[key](newObj));
}
return newObj as unknown as D;
}
The idea is that i can pass any object of functions that i want, but typescript for some reason requires that i pass all the properties that exist on type , otherwise it throws an error
For instance if D is
interface Destination {
name: string;
bio: string;
names: string[];
profession: {
field: string;
level: string;
};
And i call the function as:
transform<Source, Destination>(sourceData, "Destination", {
name: () => {},
bio: () => {},
profession: () => {},
});
}
It will throw an error:
Argument of type '{ name: () => void; bio: () => void; profession: () => void; }' is not assignable to parameter of type 'ForMembers<Destination, Source>'. Property 'names' is missing in type '{ name: () => void; bio: () => void; profession: () => void; }' but required in type 'ForMembers<Destination, Source>'.
If i add the missing property - 'names', the error goes away, however i want to pass only the properties i need, not all of them. So the question is this - How to make the function to take as forMembers any combination of properties of D, not necessarily all of them?
CodePudding user response:
You can tell TS that all properties of an object are optional, using Partial
:
forMembers?: Partial<ForMembers<S>>