Marco Danzo
Marco Danzo

Reputation: 9

Typescript: Types of property 'constructor' are incompatible

I'm new in Typescript and I'm trying to migrate a JS customized library to TS by adding all types. This is an easy example of what I am try to do. Original JS File (Class) 'parser.js':

class Parser {
  constructor(name){
    this.name = name;
  }
} 
module.exports = Parser;

Types file 'parsertypes.d.ts':

export type tbrat = {
  constructor(name:string): tbrat;
};

TS utilizing file 'utilize.ts':

import Parser from './parser';
import {tbrat} from './parsertypes';
const n: tbrat = new Parser('hello');

ERROR:

Type 'Parser' is not assignable to type 'tbrat'. Types of property 'constructor' are incompatible. Type 'Function' is not assignable to type '(name: string) => tbrat'. Type 'Function' provides no match for the signature '(name: string): tbrat'.

I don't understand what I am missing. I can't move the original JS file to TS for particular reasons.

Upvotes: 0

Views: 2752

Answers (2)

J. Pichardo
J. Pichardo

Reputation: 3115

There are no constructors for type definitions only for classes, so you might want to use declare, something like the following will work:

class Parser {
  constructor(name){
    name;
  }
} 

declare class tbrat {
    constructor(name: string) {

    }
}

const n: tbrat = new Parser('hello');

Please also take a look at the answer from Noel Varanda.

Upvotes: 1

nowy
nowy

Reputation: 394

The same way that JavaScript has modules, TypeScript does, too.

If you were writing pure TypeScript, you would not need to do the following, as the transpiler would take care of this for you. However, as you are creating a definition file, you need to declare a module in the same way that your JavaScript code does.

You need to declare your parser module in parser.d.ts:

declare module "parser" {
  class Parser {
    constructor(name:string): void
  }

  export default Parser;
}

You then import parser as you normally would in utilize.ts:

import Parser from 'parser'

const foo = new Parser('test')

Further reading: https://www.typescriptlang.org/docs/handbook/modules.html

Upvotes: 4

Related Questions