lenny lenny - 1 month ago 7
Node.js Question

Avoid Type '{}' is not assignable to type 'X'

I'm migrating JavaScript project to TypeScript.

Using a node module in TS such as URL is causing some trouble for me:

import nodeUrl = require('url');
// ...
// this worked fine in JS
nodeUrl.format({
// just for demonstration
x: this.getX(someObj),
y: this.getY(someObj)
});


Results in:


Type '{}' is not assignable to type 'string'


This is due to the definition of that module function. From @types/node/index.d.ts:

declare module "url" {
export interface Url {
href?: string;
protocol?: string;
auth?: string;
hostname?: string;
port?: string;
host?: string;
pathname?: string;
search?: string;
query?: string | any;
slashes?: boolean;
hash?: string;
path?: string;
}

export function parse(urlStr: string, parseQueryString?: boolean, slashesDenoteHost?: boolean): Url;
export function format(url: Url): string;
export function resolve(from: string, to: string): string;
}


My question is how do you avoid/fix this error without changing the declaration file?

Answer

Should be something like:

import nodeUrl = require('url');

declare module "url" {
    export function format(url: Url): string;
    export function format(x: any, y: any): string;
    export function format(url: any): string;
}

More info about this can be found in Module Augmentation.

Comments