Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React & Fuse js with TypeScript

I have this error message when using Typescript with Fuse.js

TS2345: Argument of type '{ keys: string; }' is not assignable to parameter of type 'FuseOptions<{ 'ISBN': string; 'title': string; 'author': string; }>'. Types of property 'keys' are incompatible. Type 'string' is not assignable to type '("title" | "ISBN" | "author")[] | { name: "title" | "ISBN" | "author"; weight: number; }[]'.

Here is the code:

let books = [{
        'ISBN': 'A',
        'title': "Old Man's War",
        'author': 'John Scalzi'
    },
    {
        'ISBN': 'B',
        'title': 'The Lock Artist',
        'author': 'Steve Hamilton'
    }
]

let options = {
    keys: 'title'
}
let fuse = new Fuse(books, options)

let filterResult = fuse.search('old')

The error is when hovering over options in let fuse = new Fuse(books, options)

like image 274
R.Dixon Avatar asked Oct 26 '25 09:10

R.Dixon


1 Answers

This just tripped me up for a bit too.

The compiler moves in order from top to bottom, so by the time it's looked at options, it's inferred it's a string[], which isn't compatible with the keyof of your book type. So add a type annotation to your declaration of options.

Also, the keys should be an array of keys.

Final result:

type Book = { ISBN:string; title: string; author: string; };

let options: Fuse.FuseOptions<Book>  = {
    keys: ['title'],
};
like image 191
Daniel Hines Avatar answered Oct 28 '25 23:10

Daniel Hines



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!