Turnipdabeets
Turnipdabeets

Reputation: 6005

TS import separate type files into a single index.d.ts file

I want to separate component types into individual index.d.ts and then import those types into a final index.d.ts under my src folder. How can I import these types into a single index.d.ts without getting the error [ts] Import or export declaration in an ambient module declaration cannot reference module through relative module name.?

files:

src
 |__components  
 |  |__Text  
 |     |__index.js
 |     |__index.d.ts
 |  |__Button
 |     |__index.js
 |     |__index.d.ts
 |__index.js
 |__index.d.js

src/index.d.ts

declare module "my-module-name" { 
  export { default as Text } from "./components/Text/index.d.ts";
}

src/index.js

export { default as Text } from "./components/Text";
export { default as Button } from "./components/Button";

Upvotes: 5

Views: 5723

Answers (1)

Karol Majewski
Karol Majewski

Reputation: 25790

You don't need to use declare module. Relative paths don't work there anyway — they can be used only in module augmentation, that is when you modify an existing definition.

Start by declaring your components in their respective folders. I used just React.ComponentType, but you can be more specific.

./src/components/Button/index.d.ts

import * as React from 'react';

declare const Button: React.ComponentType;

export default Button;

./src/components/Text/index.d.ts

import * as React from 'react';

declare const Text: React.ComponentType;

export default Text;

Next, create a barrel file to re-export your components.

./src/index.d.ts

export { default as Text } from './components/Text'
export { default as Button } from './components/Button'

Now your components are accessible both from ./src and from their respective folders. If we created another catalog called consumer in the root of your project, it would have access to your components:

./consumer/index.ts

/**
 * Import the re-exported components from `./src/index.d.ts`:
 */
import { Button } from '../src/';

/**
 * Or import from their respective folders:
 */
import Text from '../src/components/Text';

Keep in mind resolving paths in this fashion requires setting "moduleResolution" to "node" in your tsconfig.json.

{
  "compilerOptions": {
    "baseUrl": ".",
    "moduleResolution": "node"
  }
}

Upvotes: 5

Related Questions