nachocab
nachocab

Reputation: 14364

How to fix 'Cannot use namespace as a type ts(2709)' in 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?

Upvotes: 58

Views: 93724

Answers (5)

chz
chz

Reputation: 9

You can import the type with:

import { SortedArray } from 'sorted-array';

Upvotes: 0

chantey
chantey

Reputation: 5827

Namespaces can be converted to types using the typeof keyword.

import * as Vector3 from './Vector3'
type Vector3 = typeof Vector3
let foo: Vector3

Upvotes: 59

Tyler Dane
Tyler Dane

Reputation: 1069

You might get this error if what you want to import is a valid interface/type inside of a 3rd party namespace.

For example, If your 3rd party library looked like this:

//sorted-array.ts

// namespace that you can't import
export declare namespace sorted-array { 

    // interface that can be imported, but is blocked because it lives in a namespace
   export interface SortedArray { 
      // precious types
   }
}

In that case, your declaration can be a little simpler.

// src/typings/sorted-array/index.d.ts

import sorted-array from "/path/to/sorted-array";

export declare type Sorted = sorted-array.SortedArray;

And you can use it like this:

import Sorted from 'src/typings/sorted-array/index.d.ts';

export class Selector {
  private mySortedArray!: Sorted;
  ...
}

Upvotes: 0

rektide
rektide

Reputation: 1584

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;

Upvotes: 31

Dmitriy
Dmitriy

Reputation: 2822

You need to export it inside module declaration:

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

  export = SortedArray;
}

Upvotes: 19

Related Questions