Strong typing for JavaScript.
By default in JavaScript, you can access any property or call any function on any variable. The only problem is that you might get a runtime error. TypeScript adds strong typing to detect and avoid these issues at the build level.
tsc hello.ts
will "compile" the .ts
file and create a .js
file.
Two stricter compiler flags:
noImplicitAny
- won't fall back to the most lenient type (any) as this partially defeats the point of TS.strictNullChecks
- null and undefined are used to signal absent or uninitialised values, and can be assigned to any typesI used Grunt to help automate the build process - see [grunt-typescript](<https://www.npmjs.com/package/grunt-typescript>)
and set up your tsconfig.json
tsconfig.json
The primitive types are string
, number
, and boolean
.
You can signify arrays using number[]
or Array<number>
(the latter is for generics).
any
is a special type that can be used to avoid typechecking errors - you can access any property, call it like a function, or assign it to/from anything.
Type Annotations are done like Go: let myName: string = "Will"
But you don't need them in most cases - it will infer the types.
Functions can have type annotations after each parameter and for a return value
function greet(name: string) {
function multiply(value: number): number {
Typically a return annotation isn't needed, as it can be inferred.
Objects can also be typed. When passed as a function parameter, you can just list its properties and their types:
function printCoord(pt: { x: number; y: number }) {
Optional properties are also valid and Swift-like. It means values can be undefined.
Union types allow you to represent any one of a given type:
function printId(id: number | string) {
But then to actually use id
, you have to narrow the type using if statements such as if (typeof id === "string")
or if (Array.isArray(x))
Type Aliases let you define a type one and refer to it by name. It works a bit like a macro.
type Point = {
x: number;
y: number;
};
function printCoord(pt: Point) {
...