Should TypeScript Interfaces Be Defined in *.d.ts Files

前端 未结 3 1175
我在风中等你
我在风中等你 2021-02-04 00:00

TypeScript newbie question. In our project, we are using some external JavaScript libraries where we needed to add *.d.ts files. I understand this use case and the reason why we

相关标签:
3条回答
  • 2021-02-04 00:43

    Another developer suggested we put [the interface] in a *.d.ts file and then we would not need to import it in order to reference it.

    Using a .d.ts vs. .ts file is unrelated to providing a type declaration in a local/module or global/script scope.

    You can export the interface ErrorFirstCallback, so others will have to import it. Or you don't use export/import to make the file a global script. Then, ErrorFirstCallback can be used without an import. It doesn't matter, if the file has a .ts or .d.ts extension in this case.

    When should interfaces that we are defining be defined in a *.d.ts file vs a *.ts file.

    What does matter is, that .d.ts files are only seen as compiler input and not emitted to your dist/build folder.

    As a good rule of thumb, you put the type in a .ts, if you want to provide it as part of an npm package or public typed API to make your life easier with the build step (it will be emitted as compiler output).

    You can use .d.ts files for internally used types of your project.

    0 讨论(0)
  • 2021-02-04 00:53

    Are you using typings? That seems to be the community way to manage third party types. That way you don't have to manage defining other developers' APIs.

    As a point of reference the Node environment d.ts appears to just define the (err, res) callbacks throughout the API (https://github.com/typed-typings/env-node/blob/master/6/node.d.ts)

    0 讨论(0)
  • 2021-02-04 01:00

    Declaration files describe the shape of external JavaScript libraries. For example using jQuery with $ will result in a TypeScript error without declaration files, because $ or JQuery is undefined. Therefor a declaration file creates an interface, so the compiler knows "if this variable is of type JQuery it must have the functions x,y,z"

    When creating interfaces for your project, you should put them where ever you like: Within one big interface-file, within an individual file for each interface, or within the file where it may belong to, BUT within a declaration file would be very inconvenient.

    Personally i like to have individual files for each module/class/interface. But its just a matter of taste.

    The only thing considering creating a declaration file is to give other developers the possibility to use you final JavaScript file(not TypeScript!) in their project.

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