interface List {
s1: (input: number) => number;
s2: (input: string) => string;
}
// https://github.com/Microsoft/TypeScript/pull/26243
type Parameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never;
const a = async () => {
type Api = <T extends keyof List>(name: T, ...input: Parameters<List[T]>) => ReturnType<List[T]>;
const api: Api = window["api"];
const x: number = await api("s1", 2);
const y: string = await api("s2", 's');
};
好的,如果你想这样做,你可以用这段代码来构造
List
从
S
// Distributive conditional type to look at each union constituent of `S`
// and keep the one with the name we are looking for.
type Lookup<SS, K> = SS extends { name: infer N } ? N extends K ? SS : never : never;
type List = {
[K in S["name"]]: Lookup<S, K>
};
有关条件类型的进一步阅读,请参阅
handbook
.