简体   繁体   English

如何在Typescript中覆盖或扩展libary类型定义

[英]How to override or extend a libary type definition in Typescript

If I import a library type declaration in Typescript. 如果我在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? 当编译器出现问题时,如何扩展该库的定义,但它是否是有效的js代码? For example validate.js type bindings are very inaccurate compared to the actual implementation. 例如,与实际实现相比,validate.js类型绑定非常不准确。 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. 与mongoose类似,我无法访问modelSchemas属性,但我需要。

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? 我怎样才能做到这一点?

Put additional typings in custom-typings.d.ts in root of src . src root中的custom-typings.d.ts中添加其他custom-typings.d.ts

custom-typings.d.ts 定制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 我-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 )? 为什么要使用ES5语法importrequire )? ES6 modules and their properties are constant. ES6模块及其属性是不变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM