使用TypeScript的React&Fuse js

时间:2018-12-04 10:28:15

标签: reactjs typescript

将Typescript与Fuse.js一起使用时出现此错误消息

  

TS2345:类型参数'{{keys:string; }'不能分配给'FuseOptions <{'ISBN':string; 'title':字符串; 'author':字符串; }>'。属性类型的“密钥”不兼容。类型'string'不能分配给类型'((“ title” |“ ISBN” |“ author”)[] | {名:“标题” | “ ISBN” | “作者”;重量: } []'。

代码如下:

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')

错误是悬停在let fuse = new Fuse(books, options)中的选项上

1 个答案:

答案 0 :(得分:1)

这也让我有点绊倒。

编译器从上到下依次移动,因此在查看options时,推断它是string[],与您的keyof不兼容书籍类型。因此,在选项声明中添加类型注释。

此外,keys应该是键的数组。

最终结果:

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

let options: Fuse.FuseOptions<Book>  = {
    keys: ['title'],
};