我正在try 实现一个UI,在该UI中,客户端可以使用许多属性中的任何一个进行搜索.AFAIK这可以通过联合类型来实现.到目前为止,我的实现如下所示
interface GivenNameSearchTerm {
readonly givenName: string;
}
interface FamilyNameSearchTerm {
readonly familyName: string;
}
type SearchTerm = GivenNameSearchTerm | FamilyNameSearchTerm;
const search = (input: SearchTerm): Results[] => {
// do stuff
}
现在,我想通过允许用户 Select 要搜索的属性及其值来调用search
函数.
根据this other question,可以使用条件类型来缩小可能键的范围
type SearchInput<T> = T extends T ? keyof T : never;
const test = (key: SearchInput<SearchTerm>, value: string) => {
search({ [key]: value });
}
这种方法使我可以缩小key
可以具有的值,只允许givenName
或familyName
,但TypeScrip显示以下错误:
TS2345: Argument of type { [x: string]: string; } is not assignable to parameter of type SearchTerm
Property familyName is missing in type { [x: string]: string; } but required in type FamilyNameSearchTerm
如果我硬编码的关键一切工作,但用户应该能够 Select 它.任何 idea ?
我查看了关于narrowing的文档,但在本例中,我不需要缩小类型,只需接受任何联合类型.虽然通过缩小类型没有错误,但这会导致重复代码:
const test = (key: SearchInput<SearchTerm>, value: string) => {
switch (key) {
case 'givenName':
search({ [key]: value });
break;
case 'familyName':
search({ [key]: value });
break;
}
}