4

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".

2 Answers 2

6

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()
}

Sign up to request clarification or add additional context in comments.

2 Comments

getPropertiesArray(props.charterers.payload, 'key') calling the function with other key than 'ID' throws an error . Argument of type '"key"' is not assignable to parameter of type '"ID" | undefined'.
Yes that was the case , typescript couldn't infer type for that .
5

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.

5 Comments

In that case, tslint throws an error K declared but its value never used
Oh I see - and I'm guessing you can't just make the 2nd parameter of type String? That's probably what's causing the error, since you're passing in a String as the default value....optionally can you typecast, something like property = (K) "ID"?
Could you please update your answer with your suggestion? I didn't get your mind
Updated, but also with a little more searching, I found this question, which I think is your core issue: stackoverflow.com/questions/57151263/…
I checked it out. I didn't like the solution. I believe it can be solved very easily. Anyway, thanks a lot.

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.