Typescript 泛型api类型的类型脚本?

Typescript 泛型api类型的类型脚本?,typescript,Typescript,例如,api类似于api('serviceName',{data:1}),由api的客户端调用。请注意,客户端不一定与服务器运行在同一台机器上 api看起来像: export const api = async (type: string, payload: Object) => { const res: any = await request .post(`someurl.com/api`) .json({data: ejson.stringify({type, pa

例如,api类似于
api('serviceName',{data:1})
,由api的客户端调用。请注意,客户端不一定与服务器运行在同一台机器上

api
看起来像:

export const api = async (type: string, payload: Object) => {
  const res: any = await request
    .post(`someurl.com/api`)
    .json({data: ejson.stringify({type, payload})});
  return res;
};
服务器端看起来像这样:

const apiRemote = (apiName, apiInput) => {
  return apiList[apiName](apiInput)
}
请注意,客户端不能直接包含
apiRemote
文件

如何使
api
具有类型

类似,但在flowtype中:

一些几乎有效的示例:

interface S1 {
  name: 's1',
  input: number,
  output: number,
}

interface S2 {
  name: 's2',
  input: string,
  output: string,
}

interface List {
  s1: S1;
  s2: S2;
}

const a = async () => {
  type Api = <T extends keyof List>(name: T, input: List[T]['input']) => List[T]['output'];
  const api: Api = window["api"];
  const x: number = await api("s1", 2);
  const y: string = await api("s2", 's');
};

有关条件类型的进一步阅读,请参阅。

谢谢,这很有帮助,但我对所需内容感到困惑,我在edit2.Wow中进行了更新!谢谢太棒了。我在哪里可以读到更多关于这类东西的资料?你也能简单解释一下发生了什么事。这有点复杂,可能也会帮助其他人。也可以转换为更简单的方式(可能类似于if-else,而不是2个三元运算符?)
interface S1 {
  name: 's1',
  input: number,
  output: number,
}

interface S2 {
  name: 's2',
  input: string,
  output: string,
}

type Service<T extends { input: any, output: any }> = (input: T['input']) => Promise<T['output']>

// I'd like not to have this one because now I have to enforce manually that
// s1 key in List is the same as S1["name"].
// I think makes sense for the name to be in the S1 not in this List.
interface List {
  s1: S1;
  s2: S2;
}

// I'd like to keep it in this format instead
type S = S1 | S2;

const a = async () => {
  // But in this place, if I replace `List[T]` with `S['input']` will lose the types.
  type Api = <T extends S["name"]>(name: T, input: List[T]['input']) => Promise<List[T]['output']>;
  const api: Api = window["api"];
  const x: number = await api("s1", 2);
  const y: string = await api("s2", 's');
};
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');
};
// 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>
};