You can use JSDoc to set the types of variables. In this example, assigning an empty array to the variable
names doesn't tell the type system anything, but if we use the JSDoc
@type annotation, then we indicate to TypeScript that this variable should only be an array of strings. As this is documentation, it also tells you and your team what kind of variable this is.
If you later try to assign a value with a different type to
names or try to add an element of the wrong type, TypeScript will complain about it.
You can also define complex types with @typedef.
With JSDoc annotations in place, you can import types from one file into another, meaning you don't have to repeat yourself and redefine types in multiple places.
You can also type the parameters and the return value of functions:
There's more to JSDoc than this, and you can read up on the JSDoc annotations that TypeScript supports in the TypeScript documentation.
Writing TypeScript declaration files is the closest this article will get to writing TypeScript itself. A declaration file declares the types of classes, functions and variables in TypeScript syntax without defining the contents.
To use a declaration file to define the
TeamMember type, from above, you would create a teamMember.d.ts file and enter the following:
Importing your types from a declaration file keeps your type definitions separate from your code and gives you all of the expressiveness of the TypeScript type system. Adding declaration files like this to libraries that you write means that other projects can also install the library and access the types.