[英]How to extend a module from npm using TypeScript?
我正在使用帶有TypeScript的joi和@ types / joi 。 Joi有一個extend方法,它允許通過返回一個新實例來擴展joi,而無需修改原始的joi庫。 我用它創建了一個擴展實例。
為這個擴展實例創建定義,我試圖Module Augmentation
所描述這里使用以下代碼:
declare module 'joi' {
// Add a new Schema type which has noChildren() method.
interface CustomSchema extends ObjectSchema {
noChildren(): this;
}
}
但是,正如預期的那樣,這會通過擴充來修改原始定義。 我想要的是為擴展實例創建定義,它繼承原始內容而不修改它。
擴展Joi
也創建如下:
import * as Joi from 'joi';
const JoiExtended = Joi.extend({...some implementation...})
// How to export?
// export * from 'Joi' ---> In this case, original non-extended Joi is exported
// export default JoiExtended ---> Imported `Joi` reports: Cannot find namespace 'Joi'
Joi
? PS我正在學習TypeScript並尋找這個問題的答案但是找不到答案,也許,因為我不習慣使用打字稿術語並搜索錯誤的術語。
Joi.extend
返回的新實例joi
模塊,您可以使用導出的Root
類型。
您需要創建一個擴展Joi.Root
的接口和另一個擴展您正在擴展的基本joi
類型的接口。 您可以像導入任何其他對象一樣導出自定義joi
實例。
下面是使用extend()
上的API文檔示例中的round()
和dividable()
規則的示例。
import * as Joi from 'joi';
interface ExtendedNumberSchema extends Joi.NumberSchema {
round(): this;
dividable(num: number): this;
}
interface ExtendedJoi extends Joi.Root {
number(): ExtendedNumberSchema;
}
const customJoi: ExtendedJoi = Joi.extend((joi) => ({
base: joi.number(),
name: 'number',
language: {
round: 'needs to be a rounded number', // Used below as 'number.round'
dividable: 'needs to be dividable by {{q}}'
},
pre(value, state, options) {
if (options.convert && this._flags.round) {
return Math.round(value); // Change the value
}
return value; // Keep the value as it was
},
rules: [
{
name: 'round',
setup(params) {
this._flags.round = true; // Set a flag for later use
},
validate(params, value, state, options) {
if (value % 1 !== 0) {
// Generate an error, state and options need to be passed
return this.createError('number.round', {v: value}, state, options);
}
return value; // Everything is OK
}
},
{
name: 'dividable',
params: {
q: joi.alternatives([joi.number().required(), joi.func().ref()])
},
validate(params, value, state, options) {
if (value % params.q !== 0) {
// Generate an error, state and options need to be passed, q is used in the language
return this.createError('number.dividable', {v: value, q: params.q}, state, options);
}
return value; // Everything is OK
}
}
]
}));
const schema = {
a: customJoi.number().round().dividable(3)
};
const result = customJoi.validate({a: 4.1}, schema); // will fail because 4 is no divisible by 3
console.log(result);
export = customJoi;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.