问题描述
我已经编写了自己的TypeScript ORM,其中用于sql INSERT的模型类与从数据库中选择现有行时使用的模型类是分开的。原因是我所有的模型都是不可变的...
下面是一些简单的示例,假设有两个sql表:user
和blog
,这意味着我有4个单独的模型:
class Insert_user {
readonly id:string;
readonly username:string;
readonly joined_at?:string; // Optional because: sql will set a default value of Now() during INSERT
constructor(props:Insert_user) { Object.assign(this,props); Object.freeze(this); }
}
class Select_user {
readonly id:string;
readonly username:string;
readonly joined_at:string; // we kNow it will always be there when pulling an existing record out
constructor(props:Select_user) { Object.assign(this,props); Object.freeze(this); }
}
class Insert_blog {
readonly id:string;
readonly blog_title:string;
readonly view_count?:number; // Optional because: sql will set a default value of 0 during INSERT
constructor(props:Insert_blog) { Object.assign(this,props); Object.freeze(this); }
}
class Select_blog {
readonly id:string;
readonly blog_title:string;
readonly view_count:number; // we kNow it will always be there when pulling an existing record out
constructor(props:Select_blog) { Object.assign(this,props); Object.freeze(this); }
}
我希望能够编写多个可以接收“插入”模型的函数,但是打字系统会根据输入知道返回相应的“选择”模型。例如
type AnyInsertModel = Insert_user | Insert_blog;
type AnySelectModel = Select_user | Select_blog;
function takeAnInsertModelButReturnItsSelectModel(insertModel:AnyInsertModel) {
// data from insert model is INSERTed into sql database
// after the INSERT is done,the data is then SELECTed from the
const selectModel = {/* data that we pulled using SELECT */} as Select_???;
}
/**
* I want the type for the output variable below to be Select_user
*/
const selectedUser = takeAnInsertModelButReturnItsSelectModel(new Insert_user({id: 'd110ec70-9a16-4ad0-a73b-82e241a054eb',username: 'Neo'}));
/**
* I want the type for the output variable below to be Select_blog
*/
const selectedBlog = takeAnInsertModelButReturnItsSelectModel(new Insert_blog({id: '2068bc9d-f19d-4043-a13a-6af4b2207be2',blog_title: 'I liek milk'}));
我想简单地从函数参数中“转换”类型,即我不想在每个函数调用中都给出冗余的泛型(尽管泛型可以在函数定义本身上使用),但是看到参数是已经输入开头。
好像我自己已经解决了(下面的答案),但也热衷于了解其他方法。
解决方法
在编写此方法时尝试了一堆方法时,我遇到了"conditional types",它似乎恰好适合于此:
type InsertToSelect<T extends AnyInsertModel> =
T extends Insert_user ? Select_user :
T extends Insert_blog ? Select_blog :
never
function takeAnInsertModelButReturnItsSelectModel<InputGeneric extends AnyInsertModel>(insertArg: InputGeneric): InsertToSelect<InputGeneric> {
const selectedModel = someCodeThatInsertsAndThenSelects();
return selectedModel as InsertToSelect<InputGeneric>;
}
但是渴望知道是否还有其他方法可行?