【发布时间】:2021-09-08 07:52:55
【问题描述】:
我正在为我的宠物项目为 Postgres DB 开发自己的 ORM。但我面临的问题是打字稿认为存在与我实际得到的类型不同的类型。代码如下:
//model.ts
export class TestModel {
static tableName: string;
constructor(data:any) {
}
public static async findById(id: number) {
const client = await pool.connect();
const result: QueryResult<any> = await client.query(
`select * from public."${this.tableName}" where id = ${id}`
);
const results = result ? result.rows : null;
client.release();
if (!results) return null;
return new this(results[0]);
}
}
export class TestWeekModel extends TestModel {
static tableName = 'Week';
id: any;
current_week: any;
constructor(data: any) {
super(data);
this.id = data.id;
this.current_week = data.current_week;
}
}
//test.ts
import { TestModel, TestWeekModel } from "./database/model";
async function test() {
const week = await TestWeekModel.findById(1);
console.log(week);
}
test();
实际输出为:TestWeekModel { id: 1, current_week: 2 }
但是 typescript 说变量“week”的类型是“const week: TestModel | null”。为什么 typescript 认为那周是 TestModel 类型而不是 TestWeekModel?如何获得所需的 TestWeekModel 类型?
【问题讨论】:
标签: typescript types