Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: refactor types #261

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ class Model<T> extends EventEmitter {
Document: { new<T>(data: T): Document<T> };
Query: { new<T>(data: Document<T>[]): Query<T> };
_database: Database;
[key : string]: any;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

warehouse/src/model.ts

Lines 79 to 82 in af981d3

Object.assign(this, schema.statics);
// Apply instance methods
Object.assign(_Document.prototype, schema.methods);

Solve the above code, but as with #252, it's not a good solution. Model knows nothing about static and method types in Schema.
@SukkaW Do you have any good solutions?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was going to add another generic for setting the type of static and method, but its not possible to act directly on the class.

interface Extra {
  statics: Record<string, (...args: any[]) => any>;
  methods: Record<string, (...args: any[]) => any>;
}

type AddThis<R extends Record<string, (...args: any[]) => any>, T> = {
  [K in keyof R]: (this: T, ...args: Parameters<R[K]>) => ReturnType<R[K]>;
}

class Schema<T = any, K extends Partial<Extra> = Extra> {
  statics!: K['statics'] extends Record<string, (...args: any[]) => any> ? AddThis<K['statics'], T> : Record<string, (this: T, ...args: any[]) => any>;
  methods!: K['methods'] extends Record<string, (...args: any[]) => any> ? AddThis<K['methods'], T> : Record<string, (this: T, ...args: any[]) => any>;

}

interface AssetSchema {
  _id: string
}

const a = new Schema<AssetSchema, {
  statics: {
    add: (a: number, b: number) => number;
  }
}>().statics.add // <-- (this: AssetSchema, a: number, b: number) => ReturnType<(a: number, b: number) => number>

const b = new Schema<AssetSchema>().methods // <-- AddThis<Record<string, (...args: any[]) => any>, AssetSchema>

class Model<T, K extends Partial<Extra> = Extra> {
  schema!: Schema<T, K>
  // [key in keyof K['statics']]: K['statics'][key] illegal
}


/**
* Model constructor.
Expand Down
Loading