打字稿:带有数组提供的键的部分接口

Typescript: Partial interface with keys supplied by array

我正在针对 Web api 进行编程,对于某些字段,如果您在查询中指定它们,则只有 returns 它们。

{a:"hello", b:"world", c:"of goo", d:"i am always present"}

我打电话给

api.getResponse(["a","b"])

我会得到

{a:"hello", b:"world", d:"i am always present"}

回应。

我如何用 typescript 的类型语言表达它?

您可以在单独的接口上声明始终存在的字段和可选字段,然后使用 Pick 选择正确的字段:

interface AlwaysPresentFields {
    d: string;
}

interface OptionalFields {
    a: string;
    b: string;
    c: string;
}

type ApiResponse<F extends keyof OptionalFields> = AlwaysPresentFields & Pick<OptionalFields, F>;

function getResponse<F extends keyof OptionalFields>(fields: F[]): ApiResponse<F> {
    // Implementation
}

在高级打字稿中,我们可以使用 Partial、Pick、Readonly。

如您的情况,可以使用 keyof ,Partial 。使用 Pick 也可以实现相同的效果:docs

interface IResponse {
  a: string;
  b: string;
  c: string;
  d: string;
}

const getResponse = (responseKeys: Array<keyof IResponse>): Partial<IResponse> => {
  const responseWithFilteredKeys: Partial<IResponse> = {};
  const response: IResponse = {
    a: 'a',
    b: 'a',
    c: 'a',
    d: 'a',
  };
  responseKeys.forEach((key: keyof IResponse) => {
    responseWithFilteredKeys[key] = response[key];
  });
  return responseWithFilteredKeys;
};

const filterdUserResponse: Partial<IResponse> = getResponse(['a', 'b']);