【问题标题】:HashId for AngularAngular 的 HashId
【发布时间】:2018-04-18 20:32:30
【问题描述】:

我正在尝试在 Angular Last 版本项目中使用 http://hashids.org

我找到了这个定义文件:

// 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;
} 

但是当我尝试在我的 Angular 项目中使用此代码时:

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

我收到了这个错误:

错误 TS2351:不能将“new”与类型缺少的表达式一起使用 调用或构造签名。

在我的本地它可以正常工作,没有问题。但我尝试编译一个生产设置,但它不起作用。

【问题讨论】:

  • 您发布的代码还不够,因为这主要取决于您如何使用此定义。请提供可以复制问题的stackoverflow.com/help/mcve - stackblitz、repo 等。
  • 问题在于Hashids的导入,请分享你是如何导入Hashids的
  • 我用我的导入更新了代码。 @NagaSaiA
  • 从'hashids'导入Hashids;
  • 在定义中是 default 导出。它应该与默认导入一起使用,而不是*。由于它是 CommonJS 模块,它可能应该与 esModuleInterop 选项一起使用,请参阅stackoverflow.com/a/49722246/3731501

标签: javascript angular typescript hashids


【解决方案1】:

问题在于 Hashids 导入的方式,使用下面的选项默认导入 hashids

import Hashids from 'hashids';

使用 * 或 {} 进行命名导入,Hashids 在导入为命名导入时抛出以下错误(默认名称除外)

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

使用默认名称(因为默认导出也是名称为默认的命名导出)

import {default as Hashids} from "hashids";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 1970-01-01
    相关资源
    最近更新 更多