我有一个类:
export class DataAccess {
tableName: string;
constructor({ tableName }: { tableName: string }) {
this.tableName = tableName;
}
async getWhere(where: any, { single = false } = {}) {
const options: { limit?: number } = {};
if (single) {
options.limit = 1;
}
const results = await someDBobj[this.tableName].find(where, options);
if (!single) {
return results;
}
return results.length ? results[0] : null;
}
}和一个子类:
import { DataAccess } from "./data-access";
type UsersTable = {
id: string;
email: string;
password: string;
createdAt: Date;
};
export default class Users extends DataAccess {
columns: { [P in keyof UsersTable]: string };
constructor() {
super({
tableName: "users"
});
this.columns = {
id: "id",
email: "email",
password: "password",
createdAt: "createdAt"
};
}
}并使用Users类:
await users.getWhere(
{
email: user,
password
},
{
single: true
}
);如何在父DataAccess类中设置where: any的类型,以便它知道调用它的是Users子类?
发布于 2020-02-19 00:16:37
您可以使用泛型类
export class DataAccess<T> {
columns: { [P in keyof T]: string };
tableName: string;
constructor({ tableName }: { tableName: string }) {
this.tableName = tableName;
}
async getWhere(where: Partial<T>, { single = false } = {}) {
const options: { limit?: number } = {};
if (single) {
options.limit = 1;
}
const results = await someDBobj[this.tableName].find(where, options);
if (!single) {
return results;
}
return results.length ? results[0] : null;
}
}import { DataAccess } from "./data-access";
type UsersTable = {
id: string;
email: string;
password: string;
createdAt: Date;
};
export default class Users extends DataAccess<UsersTable > {
constructor() {
super({
tableName: "users"
});
this.columns = {
id: "id",
email: "email",
password: "password",
createdAt: "createdAt"
};
}
}发布于 2020-02-19 00:21:44
看起来您只是为了获得数据形状的专门化而扩展了类。在这种情况下,您可以这样做:
class DataAccess<T> {
columns: { [P in keyof T]: string };
tableName: string;
constructor({ tableName, columns }: { tableName: string, columns: { [P in keyof T]: string } }) {
this.tableName = tableName;
this.columns = columns;
}
async getWhere(where: Partial<T>, { single = false } = {}) {
const options: { limit?: number } = {};
if (single) {
options.limit = 1;
}
const results = await someDBobj[this.tableName].find(where, options);
if (!single) {
return results;
}
return results.length ? results[0] : null;
}
}
type UsersTable = {
id: string;
email: string;
password: string;
createdAt: Date;
};
const user = new DataAccess<UsersTable>({tableName: ""users", columns: {
id: "id",
email: "email",
password: "password",
createdAt: "createdAt"
};})https://stackoverflow.com/questions/60284771
复制相似问题