Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write the type definition for a module with a default export

I want to write a type definition for storybook-router. It needn't be that accurate, since this is a minor development tool (i.e. anys are acceptable), but I can't even seem to get that to work.

What I want to represent is:

import StoryRouter from 'storybook-router';

...in which StoryRouter is a function that matches the interface StoryDecorator from @types/storybook__react.

I tried the following definition file:

import { StoryDecorator } from '@storybook/react';

declare type StoryRouter = StoryDecorator;

export default StoryRouter;

Unfortuantely, that results in the following error:

TS7016: Could not find a declaration file for module 'storybook-router'. '/<path snipped>/node_modules/storybook-router/dist/StoryRouter.js' implicitly has an 'any' type. Try npm install @types/storybook-router if it exists or add a new declaration (.d.ts) file containing declare module 'storybook-router';

However, if I use that final example (declare module 'storybook-router'), I can't seem to figure out how to set a default export.

What's the correct way to represent this type?

like image 332
Vincent Avatar asked Dec 20 '17 10:12

Vincent


People also ask

What is export default TypeScript?

Default exports are meant to act as a replacement for this behavior; however, the two are incompatible. TypeScript supports export = to model the traditional CommonJS and AMD workflow. The export = syntax specifies a single object that is exported from the module.

Why would you create a default export in a module?

Default Exports: Default exports are useful to export only a single object, function, variable. During the import, we can use any name to import.

What are the two types of module exports in JavaScript?

Every module can have two different types of export, named export and default export. You can have multiple named exports per module but only one default export. Each type corresponds to one of the above syntax.


1 Answers

You don't import in a .d.ts file, you just declare the module.
Usually, it looks like this (simplest use-case with any):

// storybook-router.d.ts
declare module 'storybook-router' {
    const StoryDecorator:any;
    export default StoryDecorator;
}
like image 174
Lusito Avatar answered Nov 15 '22 06:11

Lusito