Nick
Nick

Reputation: 4223

Twitter Typeahead - Bloodhound Error in Typescript

I'm following the pre-fetch example from the Typeahead site but I'm using Typescript.

I've pulled in the typeahead.d.ts file and it's ok until I try to use a Bloodhound instance as the dataset source.

The example looks like this:

var countries = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  // url points to a json file that contains an array of country names, see
  // https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json
  prefetch: '../data/countries.json'
});

// passing in `null` for the `options` arguments will result in the default
// options being used
$('#prefetch .typeahead').typeahead(null, {
  name: 'countries',
  source: countries
});

So my translation into Typescript looks like this:

// typeahead for the employees box
var emps = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.whitespace,
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  prefetch: { url: prefetchUrl }
});

$("#employee").typeahead(null, {
  name: "emps",
  source: emps
});

Either I've translated the JS wrong or the d.ts file is wrong because the following error occurs:

Argument of type '{ name: string; source: Bloodhound<{}>; }' is not assignable to parameter of type 'Dataset'.

Types of property 'source' are incompatible.

Type 'Bloodhound<{}>' is not assignable to type '(query: string, cb: (result: any) => void) => void'.

Can anyone either tell me what I've done wrong or what I need to amend in the d.ts file to get this to compile?

The javascript that is created by this actually works fine, but the Typescript errors are preventing my project from building.

Cheers.

Upvotes: 0

Views: 1795

Answers (1)

Brocco
Brocco

Reputation: 64863

The definition of DataSet (what you're assigning source to be) is:

source: (query: string, cb: (result: any) => void) => void;

Where you are trying to pass it the type of a Bloodhound object.

I would presume that there has been a change to the actual API or the d.ts file is just not up to date.

After further exploration into the project's source code it appears that the library does take a Bloodhound object for source...

// use duck typing to see if source is a bloodhound instance by checking
// for the __ttAdapter property; otherwise assume it is a function
this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source;

Reference

That being said, I would update the d.ts on definitely typed via pull request or by contacting the authors.

Edit

Possible update to the d.ts:

source: (query: string, cb: (result: any) => void) => void | Bloodhound;

Upvotes: 2

Related Questions