Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extend a namespace from package typings

I'm trying here to extend a namespace from package typings, @typings/fullcalendar.

/// <reference path="./types/fullcalendar" />

import * as fullcalendar from 'fullcalendar';
import { TimeGrid } from 'fullcalendar';

// TimeGrid and fullcalendar.views are used then

Originals typings can be seen here.

And fullcalendar-custom.d.ts is

import * as FC from 'fullcalendar';

export as namespace FC;

declare class TimeGrid { prepareHits() }

declare let views: any;

This results in type errors, so it is obvious that fullcalendar namespace wasn't extended properly:

TS2305: Module '".../node_modules/@types/fullcalendar/index"' has no exported member 'TimeGrid'.

TS2339: Property 'views' does not exist on type 'typeof ".../node_modules/@types/ fullcalendar/index"'.

How should this be done the right way?

Can reference directive be avoided here, considering that types directory is specified in typeRoots?

The application is bundled with Webpack and awesome-typescript-loader, so the behaviour may differ from other compilation methods. At some point types seemed to be ok in IDE inspections (WebStorm) but still got type errors on compilation.

like image 944
Estus Flask Avatar asked Jun 21 '17 12:06

Estus Flask


People also ask

How do I refer a namespace in a file student ts?

To use it, it must be included using triple slash reference syntax e.g. ///<reference path="path to namespace file" /> . Must import it first in order to use it elsewhere. Compile using the --outFile command. Compile using the --module command.

How do I import a namespace in TypeScript?

Use a file tsconfig.@Pavel_K In the TypeScript handbook: "To reiterate why you shouldn't try to namespace your module contents, the general idea of namespacing is to provide logical grouping of constructs and to prevent name collisions.


1 Answers

We can import a namespace in a non-declaration .ts, and export it again as a extended type:

// custom-fc.ts : enhances declaration of FC namespace
import * as origFC from "fullcalendar";

declare namespace Complimentary {
    class TimeGrid {
        prepareHits(): void;
    }
    let views: any;
}

// apply additional types to origFc and export again
export const FC: (typeof Complimentary & typeof origFC) = origFC as any;

 

// use-fc.ts : consumer of extended declaration
import { FC } from "./custom-fc";

console.log(FC.TimeGrid);
console.log(FC.views);

(This somehow differs from your scenario, in that I'm using @types/ packages and webpack ts-loader, but you should be able to do something similar.)

like image 55
Jokester Avatar answered Sep 28 '22 05:09

Jokester