Dom
Dom

Reputation: 734

Use @types/foo definitions with another module that exports (among others) the foo package?

Let's assume I have some module called 'foo'. This module does a lot of things and it also exports mongoose.

// foo/index.js

const mongoose = require('mongoose');

module.exports = {
  // ...lots of other things and:
  mongoose, 
}

I don't own this module so I cannot change it. The foo package does not expose any types!

In my personal TypeScript project I'm importing mongoose from foo like so:

// some-file.ts

import { mongoose } from 'foo';

const carSchema = new mongoose.Schema( /* ... /* );

// etc ...

I have zero code completion and type checking at this point. How can I now install @types/mongoose and tell typescript that { mongoose } from 'foo' should use these type definitions?

Thanks!

Upvotes: 0

Views: 18

Answers (1)

0xLogN
0xLogN

Reputation: 3823

  1. You can consider making a DefinitelyTyped package @types/foo.
  2. You can make a foo.d.ts file anywhere in your repo (I use src/lib/types/augments/foo.d.ts), and then tell it that the module exports mongoose (note: @types/mongoose must be a real dependency, not a development dependency for this to work):
import Mongoose from '@types/mongoose';

declare module 'foo' {
    export const mongoose: Mongoose;
}

Upvotes: 1

Related Questions