TypeScript is a superset of JavaScript and is used to write code which is preprocessed into JavaScript at build time.
There is not yet an 'official' guide or convention but most rules used for your JavaScript code should extend to suitability for TypeScript as well.
The following advice is borrowed heavily from Basarat Al Syed
A formatter or linter for Typescript should be configured on your project,
with rules committed to your project repository for consistent developer
experience. The typescript-eslint
tool is recommended but rome also lints
and formats Typescript.
PascalCase
for name. Don't prepend with IcamelCase
for membersPascalCase
for namecamelCase
for membersPascalCase
for names.PascalCase
for enum namesPascalCase
for enum memberTypeScript enums can be problematic.
let foo = { x: 123, y: undefined };
let foo: { x: number; y?: number } = { x: 123 };
{valid:boolean, value?:Foo}
instead)return null;
return undefined;
Reason: It is conventional in Node.js e.g. error is null for NodeBack style callbacks.
IDEs should be used which allow typescript support and
automatic formatting. It's also possible to use tsfmt
on the command line.
Annotate arrays as foos: Foo[]
instead of foos: Array<Foo>
It's easier to read and is used by the TypeScript team.
type
when you might need a union or intersection.interface
when you want extends
or implements
The Google TypeScript Style Guide is a good source of best-practice with explanatory
text on why and when conventions should be followed. typescript-eslint
packages up a good
set of recommended style conventions for TypeScript, steps to integrate the package with
your project are included in the getting started guide. Some of the above rules
are effectively enforced via the package, or by default integration of typescript linting
in your IDE. Linting Typescript in WebStorm is covered by JetBrains, and in VS Code
by Microsoft.