lenny lenny - 1 year ago 70
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
// 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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download