Typescript 如何通过参数值指定命名空间中的泛型类型
我有一个从数据库中提取行的函数Typescript 如何通过参数值指定命名空间中的泛型类型,typescript,Typescript,我有一个从数据库中提取行的函数 function row<T>(table:string, id:number):Promise<T|null> { //For simplicity's sake return await Db(`SELECT * FROM ${table} WHERE id = ${id}`) } 目前我运行它时传递了一个泛型类型 const person = row<Table.person>('person', 1) T
function row<T>(table:string, id:number):Promise<T|null>
{
//For simplicity's sake
return await Db(`SELECT * FROM ${table} WHERE id = ${id}`)
}
目前我运行它时传递了一个泛型类型
const person = row<Table.person>('person', 1)
TypeScript命名空间对我们可以执行的类型操作有限制。如果我们在名称空间上尝试类型操作,编译器将告诉我们不能将名称空间用作类型或值 这里有一个变通方法,可以手动将
表
命名空间转换为表映射
类型,以便我们可以使用它执行类型操作
比我更有TypeScript经验的人可以通过生成表
类型而不是手动创建它来改进这种解决方法
namespace Table {
export type office = {
id: number
location: string
}
export type person = {
id: number
name: string
office: number
}
}
type TableMap = {
'office': Table.office,
'person': Table.person,
};
type TableKey = keyof TableMap;
function row<Key extends TableKey>(table: Key, id: number): Promise<TableMap[Key] | null> {
return null;
}
const result = row('person', 1)
名称空间表{
导出类型办公室={
身份证号码
位置:字符串
}
导出类型人员={
身份证号码
名称:string
办公室:电话号码
}
}
类型TableMap={
“office”:Table.office,
“person”:Table.person,
};
类型TableKey=TableMap的键;
功能行(表:键,id:number):承诺{
返回null;
}
const result=行('person',1)
这里就是它,它演示了
结果
if类型为Promise
名称空间既不是类型也不是值,因此对它们执行类型操作非常有限。您需要使用名称空间吗?谢谢!很好用。不,出于这个目的,我不需要名称空间,通过直接在TableMap
中定义类型并使用函数行
来简化示例。
function row(table:string, id:number):Promise<Table[table]|null>
namespace Table {
export type office = {
id: number
location: string
}
export type person = {
id: number
name: string
office: number
}
}
type TableMap = {
'office': Table.office,
'person': Table.person,
};
type TableKey = keyof TableMap;
function row<Key extends TableKey>(table: Key, id: number): Promise<TableMap[Key] | null> {
return null;
}
const result = row('person', 1)