How to extend a module in typescript?

Viewed 22

In my react typescript app I want to add a custom method to Yup. Here is my code:

import { AnyObject, Maybe } from 'yup/lib/types';
import BaseSchema from 'yup/lib/schema';
import * as Yup from 'yup'; 
export * from 'yup';

declare module 'yup' { // <<<<<<<<<<<<<<< Question is about this line
    interface StringSchema<TType extends Maybe<string> = string | undefined, TContext extends AnyObject = AnyObject, TOut extends TType = TType> extends BaseSchema<TType, TContext, TOut> {
        noEnclosingSpaces(message?: string): this;
    }
}

Yup.addMethod(Yup.string, 'noEnclosingSpaces', function (message) {
    return this.test({
        name: 'no-enclosing-spaces',
        message: message || 'No leading or trailing spaces are allowed.',
        test: value => typeof value !== 'string' || (!value.startsWith(' ') && !value.endsWith(' ')),
    });
});

The src-relative path of this file is ./Utils/yup.

then when time comes to use this, I do:

import * as Yup from 'Utils/yup';
...
     firstName: Yup.string().noEnclosingSpaces()
...

Everything works as expected, but if I change:

declare module 'yup' {

to

declare module 'Utils/yup' {

It still works. But I'm trying to understand why does this work? And which way is the correct way to extend an external module?

0 Answers
Related