Memmo
Memmo

Reputation: 268

How can I pass an attribute as a parameter with Typescript?

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?

Upvotes: 0

Views: 1161

Answers (2)

Soukyone
Soukyone

Reputation: 577

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]

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691715

You don't need the K parameter:

sortBy<T>(field: keyOf T, arr: T[], mode: 'Asc' | 'Desc'): T[]

Upvotes: 1

Related Questions