Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript type definition best practices

Tags:

I have read through dozens of pages trying to figure out the best way to setup my type definitions in TypeScript.

  • I used to have a typings.ts file somewhere in my project and would then import the types in each and every file they are needed, by doing something like

import {IMyCustomType} from './typings';

and inside my typings file I would declare my types like:

export interface IMyCustomType {...}

  • After doing some work with this boilerplate: https://github.com/rokoroku/react-redux-typescript-boilerplate/tree/master/types, I have realized that they use a models.d.ts in a types folder at the root of the project.

Instead of using export interface IMyCustomType {..} they use declare interface IMyCustomType {..}

This setup has one big advantage for me: I don't need to explicitly import the types in each file and the interfaces are available within the entire project directly.

Questions:

1) Is it correct that all **/*.d.ts files will be automatically imported during the compilation ?

2) Is it a good practice to use declare and make all types available to the entire project ?

3) Is there a standard directory path and name where I should put my type definitions ?

Basically I am trying to make my global interfaces automatically available everywhere in my project without having to import them explicitely. Is this something I should do and how do I setup my project to achieve this ?

UPDATE

After raising this with my team, most were against having ambient types, so we decided to import types whenever needed. To make this easier we are relying on our IDEs to automatically import said types.

like image 257
klugjo Avatar asked Nov 10 '17 06:11

klugjo


People also ask

Should you type everything in TypeScript?

Yes, you should make it a habit to explicitly set all types, it's will prevent having unexpected values and also good for readability.

Is it bad practice to use any in TypeScript?

any. ❌ Don't use any as a type unless you are in the process of migrating a JavaScript project to TypeScript. The compiler effectively treats any as “please turn off type checking for this thing”. It is similar to putting an @ts-ignore comment around every usage of the variable.


1 Answers

Since Typescript 2, you should be using d.ts files. With this approach you reduce a lot of your config files.

You can find more about it in:

  • typings vs @types NPM scope
  • https://georgedyrra.com/2017/06/04/migrating-from-typings-to-npm-types/
like image 56
Gustavo Lopes Avatar answered Oct 13 '22 19:10

Gustavo Lopes