farzher / fuzzysort

Fast SublimeText-like fuzzy search for JavaScript.
https://rawgit.com/farzher/fuzzysort/master/test/test.html
MIT License
3.96k stars 159 forks source link

Update index.d.ts typing for `scoreFn` to include the `obj` field in the callback argument. #120

Closed DaxChen closed 5 months ago

DaxChen commented 1 year ago

According to https://github.com/farzher/fuzzysort/blob/c7f1d2674d7fa526015646bc02fd17e29662d30c/fuzzysort.js#L94, the obj key exists on the results argument for the scoreFn callback.

The typing for obj does exist for KeyResult and KeysResult, but is missing for scoreFn?: (keysResult:ReadonlyArray<KeyResult<T>>) => number | null.

Example usage that fails with current typing:

let results = fuzzysort.go('chr', objects, {
  keys: ['title', 'desc'],
  scoreFn: (a) => {
    // NOTE HERE: Check the console, a contains the `obj` key!
    // However the typing is missing, so TypeScript is complaining with error message:
    // > Property 'obj' does not exist on type 'readonly KeyResult<{ title: string; desc: string; }>[]'.
    console.log(a.obj);

    return Math.max(a[0] ? a[0].score : -1000, a[1] ? a[1].score - 100 : -1000);
  },
});

Repro link: https://stackblitz.com/edit/typescript-rd4wc4?file=index.ts

This is useful when the score should be affected by the original object, for example lower the score of a particular category.

  scoreFn: (a) => {
    let score = Math.max(a[0] ? a[0].score : -1000, a[1] ? a[1].score - 100 : -1000);
    if (a.obj.category === 'some unimportant category') {
      score -= 10;
    } else if (a.obj.category === 'really unimportant category') {
      score -= 100;
    }
    return score;
  },
farzher commented 5 months ago

thank you for noticing this! will be fixed in 3.0.1