Home > Software design >  How to have an optional object field in typescript?
How to have an optional object field in typescript?

Time:11-10

I currently have the function below which works fine:

export const optionsFunc: Function = (token: string) => {
  const options = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    }
  };

  return options;
};

Now I want to modify it to add params to the options variable; params needs to be a key/value and not mandatory variable;

How can I modify the options variable and the function parameter params to do that? I'm looking for something like this in the end:

export const optionsFunc: Function = (token: string, params: any) => {
  const options = {
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  if (params) {
    const filteredParams = Object.entries(params).reduce(
      (a, [k, v]) => (v == null || v === 'null' ? a : (a[k] = v, a)), {}
    );
    options.params = filteredParams;
  }

  return options;
};

CodePudding user response:

You should probably use a Record to describe your object:

export const optionsFunc = (token: string, params?: Record<string, unknown>) => {
  const options = {
    params: {} as Record<string, unknown>,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
  };

  if (params) {
    const filteredParams = Object.entries(params).reduce<Record<string, unknown>>(
      (a, [k, v]) => (v == null || v === 'null' ? a : (a[k] = v, a)), {}
    );
    options.params = filteredParams;
  }

  return options;
};

Also, please don't annotate optionsFunc as Function. That throws away your types you put in the arrow function and the return type.

Later on, we use the Record again to describe options.params and the return type of the reduce call.

Playground

CodePudding user response:

You can do that like

interface SomeObject {
    optionalField?: fieldType;
    ...
}
  • Related