krisk / Fuse

Lightweight fuzzy-search, in JavaScript
https://fusejs.io/
Apache License 2.0
17.76k stars 753 forks source link

How do we get the type of a Fuse instance? #699

Closed eunicode closed 1 year ago

eunicode commented 1 year ago

Is there a way to import the type of a Fuse instance? I don't seem to see it here: https://github.com/krisk/Fuse/blob/master/src/index.d.ts

A simplified example of the use case would be:

let fuseInstance: null | SOMETYPE = null

fuseInstance = new Fuse(data)

A real use case would be a React component that "caches" the Fuse instance. We do this by creating a variable will point to the cached Fuse instance reference after the component mounts. So we declare the fuseRef variable and initially set it to null. The fuseRef variable should have a type that says the fuseRef variable value will either be null or a Fuse instance.

const fuseRef = useRef<null | SOMETYPE>(null)

useEffect(() => {
  fuseRef.current = new Fuse(data)
}, [fuseRef])
eunicode commented 1 year ago

Okay, I got help from the Typescript Discord channel. When you declare a class in TypeScript, you also create a type of the instance of the class. I think the old Typescript docs make this clearer than the new Typescript docs. So this should work:

import Fuse from 'fuse.js'

let myFuse: Fuse | null = null
myFuse = new Fuse(data)