Skip to content

Instantly share code, notes, and snippets.

@hasezoey
Last active September 21, 2019 11:02
Show Gist options
  • Save hasezoey/2cb25acdd62605b4d397267e9322f8c2 to your computer and use it in GitHub Desktop.
Save hasezoey/2cb25acdd62605b4d397267e9322f8c2 to your computer and use it in GitHub Desktop.
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
type MakeSomeOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
class Base {
public _id: string;
public static async create<K extends typeof Base>(
this: K,
value: NonFunctionProperties<MakeSomeOptional<InstanceType<K>, "_id">>
): Promise<InstanceType<K>> {
const doc = (new this(value)) as InstanceType<K>;
await doc.save();
return doc;
}
}
// please note that i cant just do "public _id?: string" because it will always be there, only on the creation / factory it is optional
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
type MakeSomeOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
abstract class Base {
public _id: string;
public static async create<T extends Base<any>>(this: new (...a: any[]) => T, value: NonFunctionProperties<MakeSomeOptional<T, "_id">>) {
const doc = new this(value);
await doc.save();
return doc;
}
}
// wanted is to have the class abstract to protect accidental usage
type NonFunctionPropertyNames<T> = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T];
type NonFunctionProperties<T> = Pick<T, NonFunctionPropertyNames<T>>;
type MakeSomeOptional<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
abstract class Base {
public _id: string;
public static async create<T extends Base<any>>(this: new (...a: any[]) => T, value: NonFunctionProperties<MakeSomeOptional<keyof T, "_id">>) {
const doc = new this(value);
await doc.save();
return doc;
}
}
// currently complains about "'_id' does not exist in type 'toString' | 'valueOf'"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment