TypeScript Style Guide
Grant Nestor edited this page Mar 9, 2018
·
4 revisions
- Use
PascalCase
for type names and enum values. - Use
camelCase
for function names, property names and local variables. - Use
UPPER_CASE
for global constants. - Use
_
as a prefix for private properties andI
as a prefix for interface names. - Use whole words in names when possible.
- Do not export types/functions unless you need to share them across multiple components.
- Within a file, type definitions should come first.
- Use JSDoc-style comments for functions, interfaces, enums, and classes.
- Use arrow functions over anonymous function expressions.
- Always surround loop and conditional bodies with curly braces.
- Open curly braces always go on the same line as whatever necessitates them.
-
else
goes on the same line as the closing curly brace. - Use two (2) spaces for indentation.
- Function and class signatures may exceed 80 chars; use a maximum of 80 chars for all other lines.
- Strings should always use single quotes if they do not contain interpolated values:
let foo = 'bar'; // static string
let baz = `${5 * 5}`; // interpolated string
let qux = 'These aren\'t the droids you\'re looking for.'; // escaped quotes in string
- Avoid public properties - use setters/getters.
- Do not use the
public
keyword for public members - it is implied by default. - Initialize all private properties to an initial value or
null
, unless they will be initialized in the constructor. If a basic type is used, do not add a type specifier (e.g.private _someValue = 0;
). - Ordering of members within a class should be:
static
public
protected
private
- Start with getters/setters in each scope, then methods. Protected and private properties go last.
- Abstract methods go in the same location as they would in the implemented class.
- Interface declaration:
/**
* The base message object which can be sent to a message handler.
*/
export interface IMessage {
/**
* The type of the message.
*/
type: string;
}
- If-Else block:
if (parent) {
this._parent = null;
} else if (this.isAttached) {
this.detach();
}
- Bit flags:
export enum WidgetFlag {
/**
* The widget is attached to the DOM.
*/
IsAttached = 0x1,
}
export class Widget {
/**
* Test whether the given widget flag is set.
*/
testFlag(flag: WidgetFlag): boolean {
return (this._wflags & flag) !== 0;
}
/**
* Set the given widget flag.
*/
setFlag(flag: WidgetFlag): void {
this._wflags |= flag;
}
/**
* Clear the given widget flag.
*/
clearFlag(flag: WidgetFlag): void {
this._wflags &= ~flag;
}
private _wflags = 0;
}