1

I'm programming against a web api that, for some of the fields, only returns them if you specify them in the query.

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

and I called

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

I would get

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

in response.

How do i express that in the type language of typescript?

1
  • What is you expected outcome Commented Mar 18, 2018 at 14:04

2 Answers 2

2

You can declare the always present and optional fields on separate interfaces then use Pick to choose the correct ones:

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

Muito Obrigado.
0

In Advanced typesscript we can use Partial, Pick, Readonly.

As in your case, keyof , Partial can be used. The same can be implemented in using Pick too: 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']);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.