0

I am a newbie with Angular 8.
I would like to pass an array of interfaces to a sort function, and I would like to pass interface attributes as parameters.
For now I have tried this way:

sortBy<T, K keyof T>(field: K, arr: T[], mode: 'Asc' | 'Desc'): T[] {
    const res = arr.sort((x, y) => x[field].localCompare(y[field], undefined, { sesitivity: 'base' }));

    return mode === 'Asc'
      ? res
      : res.reverse();
}

But I am noticing that the editor (VSCode) is reporting to me some inaccuracies, in particular:

enter image description here enter image description here enter image description here

I can't decipher these comments. What should I do to optimize my function?

2 Answers 2

1

You don't need the K parameter:

sortBy<T>(field: keyOf T, arr: T[], mode: 'Asc' | 'Desc'): T[]
Sign up to request clarification or add additional context in comments.

1 Comment

Now Property 'localCompare' does not exist on type 'T[keyof T]' and don't compile. While the rest is ok.
1

In your case, field is typed as an object k, and ofc, you cannot use an object as index. If you wanna call a parameter, you have 2 options :

const x = object.param;

Or

const x = object['param'];

In your case, your param 'field' need to be a string, then you will be able to do:

x[field]

3 Comments

No error on VSCode, but an error in the console ERROR TypeError: x[field].localCompare is not a function, that compromises the functioning of the sorting.
It means, your x[field] object, doesn t have a function localCompare, you tried to console.log the variable ?
My fault, I forgot an e :)

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.