Picci
Picci

Reputation: 17762

Typescript - Which is the safest and most correct way to extend type definitions defined in @types modules

The question is generic, but to make it clear I am going to use an example.

I am building an app with Nodejs and Tyepscript. I need to use readline from Nodejs. readlines uses the interface ReadLineOptions.

I have installed the type via the command npm install @types/node --save-dev. This is the type definition of ReadLineOptions that gets installed (in the current version of the type def)

export interface ReadLineOptions {
    input: NodeJS.ReadableStream;
    output?: NodeJS.WritableStream;
    completer?: Completer | AsyncCompleter;
    terminal?: boolean;
    historySize?: number;
}

When I start using ReadLineOptions I discover that the type definitions lack one property which I need, namely crlfDelay.

In order to overcome the problem, I have added the crlfDelay property to the type definition of ReadLineOptions changing the file @types/node/index.d.ts

I strongly suspect that this is not the most correct way to do such thing. I would prefer to have a method to extend the type def somewhere in my app code, but did not find a way.

Upvotes: 0

Views: 233

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249646

You can just create a new file that re-declares the module and the interface and only adds the missing properties. Typescript will automatically merge the interface definition and create a single interface that contains all properties

// readline-augmentation.d.ts
declare module "readline" {
    export interface ReadLineOptions {
        crlfDelay?: number;
    }
}

// test.ts 
import * as rd from 'readline'

var d : rd.ReadLineOptions = {
    crlfDelay : 10,
    ....
}

Upvotes: 1

Related Questions