Search code examples
typescriptangulartypingtype-definition

Why type definition (.d.ts) with Typescript - Angular2?


I have already seen other SO questions. But still confused with my question.

I have seen many examples which use Jquery(js), Toastr(js) toastr without typings and other JS library directly in angular2 app without using their type definition (.d.ts) files and they work just fine.

So,

1) basically what is gain or lose, going and not going with type definition file?

2) Angular2 files are also javascript files. So what about their type definition files ?

Note : I haven't tried with NPM so I don't know if when you actually install Angualr2 package ,it adds all related t.ds files in typings folder.


Solution

  • Typescript Definition files contain the type information for code written in Javascript.

    Javascript doesn't contain type information itself, so Typescript can't magically retrieve that information. To solve that problem Definition files are created which tell Typescript what types are being used where.

    So, you can use 3rd party libraries without a Definition file, but you'll lose out on the type safety that Typescript offers.

    For example, if you include the jQuery definition file then your IDE can now provide intellisense/auto-suggestions for the jQuery API. Also the Typescript compiler can give you a warning when you try to pass a boolean to a function that expects a string.

    So definition files aren't required for Typescript to work, but without them you lose a lot of the benefits Typescript provides.