Nanoid Typescript in a cloud function - Error: typeof import has no call signatures

Viewed 982

Importing

import * as customAlphabet from "nanoid";
var id: string = ""
const alphabet: string = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function generateID() {
      id = customAlphabet(alphabet,10)
      console.log(id)
}

Error

id = customAlphabet(alphabet,10)

This expression is not callable.
  Type 'typeof import("/Users/../API/functions/node_modules/nanoid/index")' has no call signatures.
1 Answers

You need call customAlphabet on the imported module. This gives you a generator function. You can call this generator to generate your random string using your custom alphabet set and custom length.

import * as nanoid from "nanoid";

// Your alphabet set
const alphabet = '0123456789ABCD';

// generator is a function that returns a random string
// of length 10, with alphabets from the characters in `alphabet` constant 
const generator = nanoid.customAlphabet(alphabet, 10);

// some random string
console.log(generator());
// another random string
console.log(generator());

Codesandbox link

Related