How can I infer the result type (TTarget) from TSource and the given property names (keyof TSource)?
I've the following function to copy defined properties to a new object:
export declare type PropertyNamesOnly<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
CopyProps<TSource, TTarget>(source: TSource, ...props: PropertyNamesOnly<TSource>[]): TTarget {
const result: any = {};
for (const prop of props) {
result[prop] = source[prop];
}
return result;
}
Now I can use it like that:
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");
But I don't want to define TSource and TTarget. I want this:
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 contains only property a and c
const copy = CopyProps(props, "a", "c");
How can I get the type TypeFromProps?
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];
}
}