#community-help

Troubleshooting TypeScript Error with Typesense

TLDR GM experienced an error with Typesense in TypeScript, requiring help to correct the issues. Jason helped propose solutions and adjustments to the code. Ultimately, they were able to resolve the errors and successfully implement a search function.

Powered by Struct AI

3

1

Oct 24, 2022 (14 months ago)
GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
05:40 PM
i am trying like this..dont have example in typescript too..pls help on this
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
05:41 PM
Here’s a typescript example: https://github.com/typesense/typesense-js/blob/master/doc/examples/server/documents.ts

In your code snippet, that last two lines should be:

const results = await searchClient.collections('companies').documents().search(searchParameters);

return data;
GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
05:51 PM
thanks for ur quick reply
05:51
GM
05:51 PM
{
"error": "TypeError",
"message": "searchClient.collections is not a function"
}
05:51
GM
05:51 PM
i am getting above error..
05:52
GM
05:52 PM
// const results = await searchClient.collections('companies').documents().search(searchParameters);
const results = await searchClient.collections('companies').documents('USA').retrieve();
return results;
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
05:52 PM
Could you share how you’ve instantiated searchClient?
GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
05:53 PM
const typesenseInstantsearchAdapter = new TypesenseInstantSearchAdapter({
server: {
apiKey: '2kxogtNROPlHjEBSy8pbd9f7Zxw3HcAQ', // Be sure to use an API key that only allows search operations
nodes: [
{
host: '1bf8hqds9032wpntp-1.a1.typesense.net',
path: '', // Optional. Example: If you have your typesense mounted in localhost:8108/typesense, path should be equal to '/typesense'
port: 443,
protocol: 'https',
},
],
cacheSearchResultsForSeconds: 2 * 60, // Cache search results from server. Defaults to 2 minutes. Set to 0 to disable caching.
},
// The following parameters are directly passed to Typesense's search API endpoint.
// So you can pass any parameters supported by the search endpoint below.
// query_by is required.
additionalSearchParameters: {
query_by: 'country',
},
});
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
05:55 PM
Looks like you’re using the TypesenseInstantSearchAdapter which you’d only use if you’re using Instantsearch.js which is a UI library.

In your case, in your code snippet you’re using typesense-js directly. So you want to instantiate the client like this:

https://typesense.org/docs/0.23.1/api/authentication.html
GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
06:10 PM
yes i am trying above typescript one
06:10
GM
06:10 PM
node_modules/typesense/src/Typesense/ApiCall.ts:60:7 - error TS2322: Type 'null' is not assignable to type 'ResponseType'.

60 responseType = null
~~

node_modules/typesense/src/Typesense/ApiCall.ts:95:7 - error TS2322: Type 'null' is not assignable to type 'ResponseType'.

95 responseType = null
~~

node_modules/typesense/src/Typesense/ApiCall.ts:207:86 - error TS2571: Object is of type 'unknown'.

207 Request #${requestNumber}: Request to Node ${node.index} failed due to "${error.code} ${error.message}${ ~~~~~ node_modules/typesense/src/Typesense/ApiCall.ts:207:100 - error TS2571: Object is of type 'unknown'. 207 Request #${requestNumber}: Request to Node ${node.index} failed due to "${error.code} ${error.message}${
~

node_modules/typesense/src/Typesense/ApiCall.ts:208:13 - error TS2571: Object is of type 'unknown'.

208 error.response == null ? '' : ' - ' + JSON.stringify(error.response?.data)
~

node_modules/typesense/src/Typesense/ApiCall.ts:208:66 - error TS2571: Object is of type 'unknown'.

208 error.response == null ? '' : ' - ' + JSON.stringify(error.response?.data)
~

node_modules/typesense/src/Typesense/ApiCall.ts:263:96 - error TS2454: Variable 'candidateNode' is used before being assigned.

263 Request #${requestNumber}: No healthy nodes were found. Returning the next node, Node ${candidateNode.index}
~

node_modules/typesense/src/Typesense/ApiCall.ts:265:12 - error TS2454: Variable 'candidateNode' is used before being assigned.

265 return candidateNode
~

node_modules/typesense/src/Typesense/ApiCall.ts:268:25 - error TS7006: Parameter 'node' implicitly has an 'any' type.

268 nodeDueForHealthcheck(node, requestNumber: number = 0): boolean {
~~

node_modules/typesense/src/Typesense/ApiCall.ts:290:22 - error TS7006: Parameter 'node' implicitly has an 'any' type.

290 setNodeHealthcheck(node, isHealthy): void {
~~

node_modules/typesense/src/Typesense/ApiCall.ts:290:28 - error TS7006: Parameter 'isHealthy' implicitly has an 'any' type.

290 setNodeHealthcheck(node, isHealthy): void {
~

node_modules/typesense/src/Typesense/ApiCall.ts:295:28 - error TS7006: Parameter 'node' implicitly has an 'any' type.

295 uriFor(endpoint: string, node): string {
~~

node_modules/typesense/src/Typesense/ApiCall.ts:305:7 - error TS7053: Element implicitly has an 'any' type because expression of type '"X-TYPESENSE-API-KEY"' can't be used to index type '{}'.
Property 'X-TYPESENSE-API-KEY' does not exist on type '{}'.

305 defaultHeaders[APIKEYHEADERNAME] = this.apiKey
~~

node_modules/typesense/src/Typesense/ApiCall.ts:307:5 - error TS7053: Element implicitly has an 'any' type because expression of type '"Content-Type"' can't be used to index type '{}'.
Property 'Content-Type' does not exist on type '{}'.

307 defaultHeaders['Content-Type'] = 'application/json'
~~

node_modules/typesense/src/Typesense/ApiCall.ts:311:15 - error TS7006: Parameter 'seconds' implicitly has an 'any' type.

311 async timer(seconds): Promise<void> {
~

node_modules/typesense/src/Typesense/Configuration.ts:72:5 - error TS2322: Type 'NodeConfiguration | null' is not assignable to type 'NodeConfiguration'.
Type 'null' is not assignable to type 'NodeConfiguration'.

72 this.nearestNode = options.nearestNode || null
~~

node_modules/typesense/src/Typesense/Configuration.ts:82:5 - error TS2322: Type 'boolean | undefined' is not assignable to type 'boolean'.
Type 'undefined' is not assignable to type 'boolean'.

82 this.sendApiKeyAsQueryParam = options.sendApiKeyAsQueryParam // We will set a default for this in Client and SearchClient
~

node_modules/typesense/src/Typesense/Configuration.ts:91:5 - error TS2322: Type 'Record<string, string> | undefined' is not assignable to type 'Record<string, string>'.
Type 'undefined' is not assignable to type 'Record<string, string>'.

91 this.additionalHeaders = options.additionalHeaders
~~

node_modules/typesense/src/Typesense/Configuration.ts:166:24 - error TS7006: Parameter 'array' implicitly has an 'any' type.

166 private shuffleArray(array) {
~

node_modules/typesense/src/Typesense/Documents.ts:201:35 - error TS2359: The right-hand side of an 'instanceof' expression must be of type 'any' or of a type assignable to the 'Function' interface type.

201 if (RangeError instanceof error && error?.includes('Too many properties to enumerate')) {
~

node_modules/typesense/src/Typesense/Documents.ts:201:44 - error TS2571: Object is of type 'unknown'.

201 if (RangeError instanceof error && error?.includes('Too many properties to enumerate')) {
~

node_modules/typesense/src/Typesense/Documents.ts:210:25 - error TS2345: Argument of type 'unknown' is not assignable to parameter of type 'string | undefined'.

210 throw new Error(error)
~

node_modules/typesense/src/Typesense/Errors/ImportError.ts:6:15 - error TS7006: Parameter 'message' implicitly has an 'any' type.

6 constructor(message, importResults) {
~

node_modules/typesense/src/Typesense/Errors/ImportError.ts:6:24 - error TS7006: Parameter 'importResults' implicitly has an 'any' type.

6 constructor(message, importResults) {
~

node_modules/typesense/src/Typesense/RequestWithCache.ts:22:7 - error TS2322: Type 'unknown' is not assignable to type 'T'.
'unknown' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'unknown'.

22 return requestFunction.call(requestContext, ...requestFunctionArguments)
~~

node_modules/typesense/src/Typesense/SearchOnlyDocuments.ts:22:7 - error TS2322: Type 'null' is not assignable to type 'AbortSignal'.

22 abortSignal = null
~

node_modules/typesense/src/Typesense/SearchOnlyDocuments.ts:27:7 - error TS7053: Element implicitly has an 'any' type because expression of type '"use_cache"' can't be used to index type '{}'.
Property 'use_cache' does not exist on type '{}'.

27 additionalQueryParams['use_cache'] = true
~~


Found 27 errors in 6 files.

Errors Files
15 node_modules/typesense/src/Typesense/ApiCall.ts:60
4 node_modules/typesense/src/Typesense/Configuration.ts:72
3 node_modules/typesense/src/Typesense/Documents.ts:201
2 node_modules/typesense/src/Typesense/Errors/ImportError.ts:6
1 node_modules/typesense/src/Typesense/RequestWithCache.ts:22
2 node_modules/typesense/src/Typesense/SearchOnlyDocuments.ts:22
06:10
GM
06:10 PM
i am getting this error
06:11
GM
06:11 PM
my code snippet like this..
06:12
GM
06:12 PM
import { env } from '../environment/environment';
import { ExceptionsHandler } from '../exceptionHandler/exceptionHandler';
import { DataWrapper, ErrorAzureResponse } from '../response/response';

import { Client } from 'typesense';
import Configuration, { NodeConfiguration, ConfigurationOptions } from 'typesense/src/Typesense/Configuration';
import { CollectionCreateSchema } from 'typesense/src/Typesense/Collections';

const typesense = new Client({
nodes: [
{
host: '1bf8hqds9032wpntp-1.a1.typesense.net',
port: 443,
protocol: 'http',
} as NodeConfiguration,
],
apiKey: '2kxogtNROPlHjEBSy8pbd9f7Zxw3HcAQ',
numRetries: 3, // A total of 4 tries (1 original try + 3 retries)
connectionTimeoutSeconds: 120, // Set a longer timeout for large imports
logLevel: 'debug',
} as ConfigurationOptions);

const SearchExceptionHandler = (e: any) => {
throw new ErrorAzureResponse({ error: 'INTERNAL_SERVER_ERROR', message: e });
};

export class Search {
async getTypesearch(latitude: number, longitude: number) {
const searchParameters = {
q: 'USA',
query_by: 'country',
group_by: 'country',
group_limit: '1',
};


const results = await typesense.collections('companies').documents('USA').retrieve();
return results;
}
}
06:18
GM
06:18 PM
i created account in typssensecloud
06:18
GM
06:18 PM
ur help is much appriciated..
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
06:19 PM
Could you try updating these import two lines to lib instead of src:

import Configuration, { NodeConfiguration, ConfigurationOptions } from 'typesense/lib/Typesense/Configuration';
import { CollectionCreateSchema } from 'typesense/lib/Typesense/Collections';
06:20
Jason
06:20 PM
It’s essentially trying to recompile the Typesense TS source code, instead of using the precompiled one in lib, and throwing those errors
GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
06:23 PM
okay thanks..let me check
06:32
GM
06:32 PM
yes ..great...its working..

1

1

06:33
GM
06:33 PM
how to pass parameters instead of id..
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
06:33 PM
Didn’t get you… Could you rephrase that with an example?
GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
06:34 PM
06:34
GM
06:34 PM
this is my json..
06:34
GM
06:34 PM
i want to search by country..
06:35
GM
06:35 PM
this is test JSON i created..for POC purpose..
06:37
GM
06:37 PM
const searchParameters = {
q: 'USA',
query_by: 'country',
group_by: 'country',
group_limit: '1',
};

const results = await typesense.collections('companies').documents().search(searchParameters);

return results;
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
06:37 PM
You want something like this:

export class Search {
  async getTypesearch(latitude: number, longitude: number, country: string) {
    const searchParameters = {
      q: country, // <== change this to a parameter
      query_by: 'country',
      group_by: 'country',
      group_limit: '1',
    };



    const results = await typesense.collections('companies').documents().search(searchParameters); // <== change this to search instead of retrieve
    return results;
  }
}
GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
06:44 PM
great...i got the error if i put group_limit
06:44
GM
06:44 PM
with out that its working.
06:45
GM
06:45 PM
async getTypesearch(latitude: number, longitude: number, country: string) {
const searchParameters = {
q: country,
query_by: 'country',
group_by: 'country',
};

const results = await typesense.collections('companies').documents().search(searchParameters);
return results;
}
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
06:45 PM
group_limit should be a number instead of a string

1

GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
06:46 PM
how to add multiple condition?
06:46
GM
06:46 PM
country ,langtitude,longtiude also in search parameters
Jason
Photo of md5-8813087cccc512313602b6d9f9ece19f
Jason
06:46 PM
You want to use filter_by search parameter for this. It’s documented under this table: https://typesense.org/docs/0.23.1/api/search.html#query-parameters

1

GM
Photo of md5-9f364f57af6f71faaf6ea963342ef3f6
GM
06:50 PM
Okay ..thanks..let me try..
06:51
GM
06:51 PM
thank you very much..

Typesense

Lightning-fast, open source search engine for everyone | Knowledge Base powered by Struct.AI

Indexed 3015 threads (79% resolved)

Join Our Community

Similar Threads

Debugging Search Issue with Typesense Server Caching

Jameshwart reported experiencing caching issues with typesense server, despite the server's default setting of not caching. Through troubleshooting steps with Kishore Nallan, they were able to confirm an issue with the Typesense Javascript client and resolved it by adding `cacheSearchResultsForSeconds: 0` after `apiKey` in the initialisation. Laura also participated in discussion, learning about server and client level caching.

66
5mo

Troubleshooting Issues with DocSearch Hits and Scraper Configuration

Rubai encountered issues with search result priorities and ellipsis. Jason helped debug the issue and suggested using different versions of typesense-docsearch.js, updating initialization parameters, and running the scraper on a Linux-based environment. The issues related to hits structure and scraper configuration were resolved.

7

131
8mo

Typescript Support and Import Issues with Typesense

Ahmad faced trouble with Typesense support for Typescript. Jason assisted by suggesting checks and solutions. Phil suggested modifying the import statement. Ultimately, the issue was resolved with a change from Jason in version `v1.1.2`.

24
25mo

Typesense Error in Unit Testing for Python

Mehdi was encountering errors while running unit tests for Typesense functionalities in Python. Through discussion with Kishore Nallan, they recognized resource constraints might be causing the issue during JSONL file import. As suggested by Kishore Nallan, adding a short sleep after the import resolved the problem.

17
23mo

Querying with Not-in in Typesense

Masahiro inquired about using not-in queries in Typesense. Kishore Nallan explained how to conduct such queries by using the "-" operator in the query string, and assisted Masahiro with issues stemming from a high number of exclusion tokens. The problem was eventually resolved by switching to the `multi_search` endpoint.

4

49
34mo