Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override or extend a libary type definition in Typescript

Tags:

typescript

If I import a library type declaration in Typescript. How can I extend the definition of that library when there's compiler issues with it, but it would be otherwise valid js code? For example validate.js type bindings are very inaccurate compared to the actual implementation. Something like shown below....

import * as validate from 'validate.js';

declare namespace validate {
  Promise: any;
  async: any;
}

Similarly with mongoose I can't access modelSchemas property but I need to.

import * as mongoose from 'mongoose';
declare namespace mongoose {
  export modelSchemas any[];
}

So if I want to add definitions to the existing types just to shut the compiler up. How can I do that?

like image 501
Richard G Avatar asked May 13 '17 10:05

Richard G


People also ask

How do you override properties in TypeScript?

Use the Omit utility type to override the type of an interface property, e.g. interface SpecificLocation extends Omit<Location, 'address'> {address: newType} . The Omit utility type constructs a new type by removing the specified keys from the existing type.

What are type definitions in TypeScript?

A type definition file is a file that ends in “. d. ts”. It is a lot like a header file in some other languages. It is a file in which you provide the type definitions for another file, the signatures without implementation.

Where do you put custom types in TypeScript?

To do this you should edit the tsconfig. json file, and add the typeRoots property under the compilerOptions property. When the property is excluded, TypeScript is automatically searching for types in the node_modules/@types folder of your project.


1 Answers

Put additional typings in custom-typings.d.ts in root of src.

custom-typings.d.ts

import * as mongoose from "mongoose";

//augment validate.js
declare module "validate.js" {
    let Promise: any;
    function async(param: any): any;
}

//augment mongoose
declare module "mongoose" {
    let modelSchemas: mongoose.Schema[]
}

my-module.ts

import validate = require("validate.js");
import mongoose = require("mongoose");
import * as Bluebird from "bluebird";

validate.Promise = Bluebird;
mongoose.Promise = Bluebird;

let schema = new mongoose.Schema({
    name: String
});

mongoose.modelSchemas = [schema];

validate.async("foo");

Why import with ES5 syntax (require)? ES6 modules and their properties are constant.

like image 152
Granga Avatar answered Sep 19 '22 12:09

Granga