Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript definitions, ES6 class, and constructors

I have a TypeScript project in which I'd like to use libmarkov from npm. It provides an ES6-importable class called Generator. You use it via new Generator('some text').

In my local project, I created a file typedefs/libmarkov.d.ts:

export class Generator {
    constructor(text: string);
    generate(depth: number);
}

I use typings to install it: typings install --save file:./typedefs/libmarkov.d.ts

However, this: let generator = new Generator('Foo Bar Baz');

...generates this compiler error:

Error:(5, 21) TS2351: Cannot use 'new' with an expression whose type lacks a call or construct signature.

I could change my constructor: constructor(text: string) {};

...but this gives:

Error:(2, 31) TS1183: An implementation cannot be declared in ambient contexts.

If it matters, I'm targeting TS 2.0.

like image 653
Paul Everitt Avatar asked Sep 12 '16 15:09

Paul Everitt


1 Answers

Since this is a js library, I suspect you load it with something like

import {Generator} from "libmarkov"

In which case your external module definition must look like

declare module "libmarkov" {

    export class Generator {
        constructor(text: string);
        generate(depth: number);
    }
}

EDIT The definition is wrong; libmarkov seems to use a default export.

declare module "libmarkov" {

    export default class Generator {
        constructor(text: string);
        generate(depth: number);
    }
}

And the import would be

import Generator from 'libmarkov'
like image 148
Bruno Grieder Avatar answered Sep 22 '22 20:09

Bruno Grieder