interface A { a?: number };
interface B { a?: string };
function replicate<
Source extends object,
Destination extends { [key in keyof Source]?: (1) }
>(
source: Source,
key: keyof Source,
destination: Destination,
converter: (value: (2)) => (3)
) {
if (source[key] !== undefined) {
destination[key] = converter ? converter(source[key]) : source[key];
}
}
const a: A = { a: 123 };
const b: B = {};
replicate(a, "a", b, (value) => value.toString());
In the sample above, what fits for the following placeholders:
- (1) - data type of value in
Destination
related to the corresponding key inSource
. - (2) - information type in
Source
associated with the specified key in parameterkey
. - (3) - data type in
Destination
linked to the specified key in parameterkey
.