javascriptangulartypescripthashids

HashId for Angular


I'm trying to use http://hashids.org in an Angular Last version project.

I found this definition file:

// Type definitions for Hashids.js 1.x
// Project: https://github.com/ivanakimov/hashids.node.js
// Definitions by: Paulo Cesar <https://github.com/pocesar>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

/// <reference types="node" />

export default class Hashids {
    private version: string;
    private minAlphabetLength: number;
    private sepDiv: number;
    private guardDiv: number;
    private errorAlphabetLength: string;
    private errorAlphabetSpace: string;
    private alphabet: string[];
    private seps: string;
    private minHashLength: number;
    private salt: string;
    constructor(salt: string, minHashLength?: number, alphabet?: string);
    public decode(hash: string): number[];
    public encode(arg: number): string;
    public encode(arg: number[]): string;
    public encode(...args: number[]): string;
    public encodeHex(str: string): string;
    public decodeHex(hash: string): string;
    public hash(input: number, alphabet: string): string;
    public unhash(input: string[], alphabet: string): number;
} 

but When I try to use in my Angular project using this code:

import * as Hashids from 'hashids';
export abstract class BaseService {
     protected getId(id: any) {
            const x = new Hashids('somesecretec');
            return x.encode(id);
     }
}

I got this error:

error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

In my local it works, without a problem. But I tried to compile a production setting and it doesn't work.


Solution

  • Issue is with the way of Hashids import, use below option to import hashids as default

    import Hashids from 'hashids';
    

    Use * or {} for named imports and Hashids throw below error on importing as named import (other than name default)

    error TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.
    

    Using default name (as default export is also a named export with name default)

    import {default as Hashids} from "hashids";