Use only tabs for indentation. Do not use spaces. Yes, spaces would be better :), it's for historical reasons.
- Always put opening curly braces on new line.
- Add a space after control flow keywords.
- Use braces for single line ifs as well
// BAD
if(foo){
// do something
}
// GOOD
if (foo)
{
// do something
}
// BAD
if (foo) bar;
// GOOD
if (foo)
{
bar;
}
Put spaces around the operator except unary operators.
var i = 0;
i++;
i = i + 1;
var s = "hello" + ", " + "world";
Don’t put spaces around the type defining colon.
var _message:String;
function foo(bar:number):String { ... }
- always add types to method signatures
- except for the void return type in classes (void return type is required in interfaces)
- add types to class variables; it is required
- try not to use the
any
type. You can always add a definition file from the excellent Definitely Typed github repo if you want to have more specific type when using a third party library.
// GOOD
public function setToRotation(radians:number)
{
var cos = Math.cos(radians);
var sin = Math.sin(radians);
...
}
Method arguments should be typed.
Leave spaces inside the braces and after the colons in object literals. If it doesn't fit easily on one line, break it into one line per field.
// GOOD
var point = { x: 100, y: 200 };
var p2 =
{
x: 100,
y: 200
};
// BAD
var point = {x:100,y:200};
An empty function should be written in one line.
function foo() {}
- No need to prefix variables declaration with public keyword, it is the default visibility in Typescript.
- All variables name must be written using the camelCase notation.
- Prefix all private variables with an underscore
- Must be written in capitals, separated by underscores if containing several words.
You can declare a class variable directly from the constructor, take advantage of it. It avoids code repetition.
class Animal
{
constructor(private name: string) { }
move(meters: number)
{
alert(this.name + " moved " + meters + "m.");
}
}
When you want to bind this
to your callback, you can use the arrow function
javascript
function Person()
{
this.age = 0;
setInterval(() => { this.age++; // |this| properly refers to the person object }, 1000); }
var p = new Person();