TypeScript custom declaration files for untyped npm modules

后端 未结 3 537
情深已故
情深已故 2021-01-31 14:05

I am consuming a React component called shiitake from npm into my project where I use TypeScript. That library does not have TypeScript declarations so I thought I would write o

相关标签:
3条回答
  • 2021-01-31 14:40

    The declaration declare module 'shiitake'; should be in a global scope. i.e. a top level declaration in a non module (where a module is a file with at least one top level import or export).

    A declaration of the form declare module '...' { } in a module is an augmentation. For more details see Typescript Module Augmentation.

    So you want this file to look like:

    declare module 'shiitake' {
    
        import * as React from 'react';
    
        export interface ShiitakeProps {
            lines: number;
        }
    
        export default class Shiitake extends React.Component<ShiitakeProps, any> { 
        }
    }
    
    0 讨论(0)
  • 2021-01-31 14:44

    In my experience, a definition file will fail in this way if it has any exports or imports declared outside the module definition. If you use an IDE with auto-import, be warned!

    0 讨论(0)
  • 2021-01-31 14:46

    I had the same problem today.

    Turns out I paste exported interfaces outside of the module declaration. The typings file I used as a template had private interfaces at the end of the file.

    So my exported interfaces were declared outside of the module declaration. This is drives typescript compiler nuts.

    Once I moved the interfaces into the module boundaries everything got fixed.

    0 讨论(0)
提交回复
热议问题