实际上,我有一个类,它将一些方法扩展为数据库表中一行的"代理".问题是,我无法让类型脚本正确地推断可以根据表传递的键集(即相关表上的列).
请考虑以下示例:
type table1 = {id: number, col1: string, col2: string}
type table2 = {id: number, colA: number, colB: number}
type DBTable = table1 | table2
type DBColumnName<T extends DBTable> = keyof T
type DBColumnValue<T extends DBTable, C extends DBColumnName<T>> = T[C]
class ProxyDBRow<T extends DBTable> {
data: T
getColumn<C extends DBColumnName<T>>(name: C): DBColumnValue<T, C> {
return this.data[name]
}
}
// proxyComponent.svelte
export let proxy: ProxyDBRow<table1> | ProxyDBRow<table2>
export let attr: DBColumnName<table1> | DBColumnName<table2>
const gc = () => {
proxy.getColumn(attr) // expression not callable error
}
换句话说,我有一个(Svelte)组件,我向该组件传递了一个代理和列名,并且我希望进行类型推断,以确定所请求的属性是该表上的有效列.
我觉得unions 并不是真正合适的解决方案,但我不知道什么才是.我在文档中查看了"条件类型",但我似乎真的无法让它正常工作.我需要它来根据代理的类型推断attr
的实际类型,我只是想不出如何正确地编写表达式.
此外,我还try 将代理的类型注释为ProxyDBRow<table1 | table2>
,但这也不能正常工作:表的联合只允许所有表共有的键,因此,例如,如果传入Table1的代理检测到将‘col1’传递到getColumn方法中的内容,则会引发错误,因为Table2没有同名的键.