简体   繁体   English

使用 TypeScript 反应和融合 js

[英]React & Fuse js with TypeScript

I have this error message when using Typescript with Fuse.js将 Typescript 与 Fuse.js 一起使用时出现此错误消息

TS2345: Argument of type '{ keys: string; TS2345:类型参数'{键:字符串; }' is not assignable to parameter of type 'FuseOptions<{ 'ISBN': string; }' 不能分配给 'FuseOptions<{ 'ISBN': string; 类型的参数'title': string; '标题':字符串; 'author': string; “作者”:字符串; }>'. }>'。 Types of property 'keys' are incompatible.属性“键”的类型不兼容。 Type 'string' is not assignable to type '("title" | "ISBN" | "author")[] |类型 'string' 不可分配给类型 '("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)错误是悬停在let fuse = new Fuse(books, options)上时

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.编译器按从上到下的顺序移动,因此在查看options时,它会推断出它是一个string[] ,它与您的书本类型的keyof不兼容。 So add a type annotation to your declaration of options.因此,在您的选项声明中添加类型注释。

Also, the keys should be an array of keys.此外, keys应该是键数组。

Final result:最后结果:

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

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

It's probably a better idea to provide your type to your Fuse instance through a generic parameter with its constructor.通过泛型参数及其构造函数将类型提供给Fuse实例可能是一个更好的主意。

So in this case, something like this would properly type all Fuse configuration and methods, not just your options object:所以在这种情况下,这样的事情会正确输入所有Fuse配置和方法,而不仅仅是你的options对象:

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

const fuse = new Fuse<Book>(books, { keys: ['title'] });

// filterResult is of type Fuse.FuseResult<Book>[]
const filterResult = fuse.search('old');

// or, if you want result of type Book[] 
const books = filterResult.map(({ item }) => item);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM