Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'Cannot use namespace as a type ts(2709)' in typescript?

Tags:

typescript

I'm loading a third-party library called sorted-array and using it like this:

import SortedArray from 'sorted-array';

export class Selector {
  private mySortedArray!: SortedArray;

  constructor() {
    this.mySortedArray = new SortedArray();
  }
}

However, I get this error: Cannot use namespace 'SortedArray' as a type.ts(2709)

So, I created this file:

// src/typings/sorted-array/index.d.ts
declare module 'sorted-array' {
  class SortedArray {
    constructor(arr: number[]);
    search(element: any): number;
  }
}

However, the error remains. What am I doing wrong?

like image 702
nachocab Avatar asked Dec 19 '18 14:12

nachocab


3 Answers

You need to export it inside module declaration:

declare module 'sorted-array' {
  class SortedArray {
    constructor(arr: number[]);
    search(element: any): number;
  }

  export = SortedArray;
}
like image 134
Dmitriy Avatar answered Oct 19 '22 22:10

Dmitriy


I was struggling to figure out how I could write a type definition for passing an external/3rd party module around. I am very much not wise nor sharp with TypeScript, but TypeScript 2.9's import() syntax seems to be the answer I was looking for (after a long long long long amount of bumbling around, being misdirected):

declare type NewRelicModule = typeof import("newrelic");

Now I can write my:

interface Config {
  newrelic?: NewRelicModule;
}

It looks like you are expecting to use the default export. Perhaps for you this might work?

declare type SortedArray = typeof import("sorted-array").default;
like image 37
rektide Avatar answered Oct 19 '22 22:10

rektide


Namespaces can be converted to types using the typeof keyword.

import * as Vector3 from './Vector3'
type Vector3 = typeof Vector3
let a:Vector3
like image 8
Peter Hayman Avatar answered Oct 19 '22 21:10

Peter Hayman