•almost 4 years ago
A TypeScript primer
- It is an Object Oriented Programming language
- It provides for optional type hints (which we'll focus on in this post)
If you're looking for more, check this concise summary of the benefits of TypeScript by our friends at Ionic. Type Definitions are the concept behind some of the most desirable benefits of TypeScript. They define the "shape" and types associated with a library's API. They enable developers to add type hints to their code base and these are checked at compilation time which helps avoid bugs. They also facilitate advanced IDE features like "code completion" which can improve the developer experience and speed up development.
Options for distributing Type Definitions
Before we go too far, it's important to note that there are a few ways that developers can create and distribute the Type Declaration File (identifiable by the
Developers and contributors of TypeScript projects
It should be no surprise that for projects written in TypeScript, it is exceptionally easy to generate Type Definitions. It is simply a matter of including the
--declaration and/or related
tsc TypeScript compiler options. From there the generated Type Definitions can be inspected and refined manually to ensure they match the developer's intent. From there it is simply a matter of including the generated
There are two main ways you can publish your declaration files to npm:
- bundling with your npm package, or
- publishing to the @types organization on npm.
If you control the npm package you are publishing declarations for, then the first approach is favored.
This bundling is convenient because the source and Type Definition is available in one place and are versioned together as part of one package.
Everyone without the ability to commit or raise PRs and publish package versions
Coding the Type Definitions
- dtslint: a utility built on TSLint for linting TypeScript declaration (.d.ts) files [dtslint on Github]
- dts-gen: creates starter TypeScript definition files for any module or library [dts-gen on Github]
In addition, the project's
package.json now declares the
"types" property. This allows the TypeScript compiler and IDEs with TypeScript support to locate the Type Declaration file and apply the Type Definitions it contains.
The end result