Is it valid to declare a typescript module multiple times?

Viewed 447

Typically I've seen module declarations in an global index.d.ts file.

declare module 'thing' {
  interface SomeChildInterface {
    myMethod(): SomeKindOfMethod;
  }
}

But what if you'd declare this in a more specific file, such as a certain function. And in a different file you'd declare the same module, but then with a different method.

Is this then 'scoped' to only that file?

Concrete example

When adding a method to an existing library:

import * as Yup from 'yup';
import { ObjectSchema, StringSchema } from 'yup';

function isUniqueValue() {
  return Yup.string().test({
    exclusive: true,
    name: 'isUniqueValue',
    message: 'Value already exists',

    test(value) {
      return this.options.context !== value
    },
  });
}

Yup.addMethod<Yup.StringSchema>(Yup.string, 'isUniqueValue', isUniqueValue);

const schema = Yup.object().shape({
  // TS2339: Property 'isUniqueValue' does not exist on type 'StringSchema '.
  name: Yup.string().isUniqueValue()
});

Now that gives me the error that the method does not exist. I can add this to the file:

declare module 'yup' {
 interface Schema<T> {
   isUniqueValue(): StringSchema;
  }
}

And then it works. But I'm not sure if that would interfere when I do this in multiple different files. And generating a generic global file for this would mean that file would have to know all the additional methods in the codebase which makes it tightly coupled.

0 Answers
Related