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

1

8

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?

Erinnerinna answered 20/12, 2017 at 10:0 Comment(0)
C
14

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;
}
Corrasion answered 20/12, 2017 at 16:19 Comment(4)
Hmm thanks, that works, and is good enough for me. Out of curiosity, is there a way to get that any to actually be the type of @storybook/react's StoryDecorator?Erinnerinna
I'm pretty sure there is a way to make a definition file for almost any js library. I'm no expert myself tho, and even if, I'd have to read up on that class?, since I have never used it. My usual approach to create a definition file is to look for libraries, which have type definitions and use a similar approach, then check how they do it. BTW, I've just found this, which seems like what you are looking for: npmjs.com/package/@types/storybook__reactCorrasion
Try searching microsoft.github.io/TypeSearch when you are looking for definitionsCorrasion
Those are type definitions for @storybook/react, whereas I'm looking for type definitions for storybook-router - which is supposed to implement StoryDecorator from the former package...Erinnerinna

© 2022 - 2024 — McMap. All rights reserved.