Norayr Ghukasyan
Norayr Ghukasyan

Reputation: 1408

How to add default value in function parameters in typescript?

I am trying to add the last piece of type in my function, but typescript complained whatever I do. I know there is a way to solve it, and need your help.

export const getPropertiesArray = <T extends object, K extends keyof T>(data: T[], property: K) => {
    return data.map(item => item[property]).sort();
};

This is my function and I need to add a default value to property, in this case, the default value is "ID".

Upvotes: 4

Views: 5486

Answers (2)

Simon Bruneaud
Simon Bruneaud

Reputation: 2567

Passing default "ID" is not assignable to constraint of object.
Indeed you should assume that ID is always a key of your object.

Here is a workaround:

// T extends { ID: any } - You may replace any by your ID type
export const getPropertiesArray = <T extends { ID: any }>(
  data: T[],
  property: keyof T = 'ID'
) => {
  return data.map(item => item[property]).sort()
}

Upvotes: 6

jbyrd
jbyrd

Reputation: 5585

In general the answer to the question as stated is simple - the format for a default parameter is myParam = "default value", so for example

function myFunc(param1 = "default value") {
    //...
}

You can read more about default parameters in Typescript here: https://www.typescriptlang.org/docs/handbook/functions.html#optional-and-default-parameters

HOWEVER: the OP's particular scenario involves a keyof parameter, which requires special handling. See Simon Bruneaud's answer for this.

Upvotes: 5

Related Questions