Is there a way to determine the result type (TTarget) based on TSource and the provided property names (keyof TSource)?
I have this function that copies specified properties to a new object:
export declare type PropertyNamesOnly<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
function CopyProps<TSource, TTarget>(source: TSource, ...props: PropertyNamesOnly<TSource>[]): TTarget {
const result: any = {};
for (const prop of props) {
result[prop] = source[prop];
}
return result;
}
Now we can use it like this:
class Props { a: string = "a"; b: string = "b"; c: string = "c"; }
const props = new Props();
const copy = CopyProps<Props, Omit<Props, "b">>(props, "a", "c");
expect(copy.a).to.equal("a");
// copy has omitted property b
expect((copy as any).b).to.be.undefined;
expect(copy.c).to.equal("c");
However, I would like to avoid defining TSource and TTarget. Instead, I want the following structure:
CopyProps<TSource>(source: TSource, ...props: PropertyNamesOnly<TSource>[]): TypeFromProps<props> {
const result: any = {};
for (const prop of props) {
result[prop] = source[prop];
}
return result;
}
// Then copy should only contain properties 'a' and 'c'
const copy = CopyProps(props, "a", "c");
How can we achieve the TypeFromProps type?
Solution:
static PickProps<
TSource,
Props extends PropertyNamesOnly<TSource>,
TTarget extends Pick<TSource, Props>>
(source: TSource, ...props: Props[]): TTarget {
const result: any = {};
for (const prop of props) {
result[prop] = source[prop];
}
return result;
}
static OmitProps<
TSource,
Props extends PropertyNamesOnly<TSource>,
TTarget extends Omit<TSource, Props>>
(source: TSource, ...props: Props[]): TTarget {
const result: any = {};
const keys = Object.keys(source).filter(k => props.some(p => p !== k)) as (keyof TSource)[];
for (const key of keys) {
result[key] = source[key];
}
}