21 August 2023
TypeScript is a typed superset of JavaScript that provides optional static typing, classes, interfaces, and other features to help build robust applications at scale. This guide will walk through the key aspects of coding in TypeScript with examples.
This material is taken from our Typescript training courses, JBI training can supply a complete solution for your training in typescript either as an individual or for an entire team. If you are interested in training or customising a course, simply get in touch and we'd be delighted to assist.
TypeScript adds type annotations to standard JavaScript syntax. These annotations allow TypeScript to analyse code for errors and inconsistencies before it runs.
// Variable with type annotation
let message: string = "Hello World!";
// Function with parameter type
function greet(name: string) {
return `Hello ${name}`;
}
Type annotations in TypeScript are optional. The compiler will infer types when not explicitly declared.
// Inferred string type
let message = "Hello World!";
// Inferred string array type
let cities = ["London", "Paris", "Tokyo"];
After compilation, the resulting JavaScript will not contain any of the type information present in the TypeScript source. The emitted code only includes runtime values.
TypeScript supports all standard JavaScript syntax and conventions. Any valid JavaScript is also valid TypeScript. This allows incremental adoption within JavaScript projects.
The basic syntax of TypeScript is very similar to JavaScript. Let's look at some examples.
Variables can be declared with let
and const
. Type annotations are optional.
let name: string = "Alice";
const age: number = 25;
Function parameters and return values can be typed.
function greet(name: string): string {
return `Hello ${name}!`;
}
function sum(a: number, b: number): number {
return a + b;
}
TypeScript supports both inline and defined object types.
// Inline type annotation
let point: {x: number, y: number} = {x: 0, y: 10};
// Defined type
interface Point {
x: number;
y: number;
}
let center: Point = {x: 0, y: 0};
Arrays can be typed in two ways. The first is a simple type annotation on the variable.
let list: number[] = [1, 2, 3];
The second way uses a generic array type.
let list: Array<number> = [1, 2, 3];
Tuples allow an array with mixed, fixed types to be defined.
let user: [string, number] = ["Alice", 25];
This covers some of the most common TypeScript type annotations. Many more exist to handle advanced scenarios.
TypeScript provides full support for ES6 classes. Class members can be marked as public
, private
, or protected
.
class Point {
// Public by default
x: number;
// Private field
private y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
// Protected method
protected distance() {
return Math.sqrt(this.x ** 2 + this.y ** 2);
}
}
TypeScript supports inheritance through the extends
keyword. Derived classes can override base methods using super
.
class ColouredPoint extends Point {
colour: string;
constructor(x: number, y: number, colour: string) {
super(x, y);
this.colour = colour;
}
// Override distance method
distance() {
return `Colour: ${this.colour}, Distance: ${super.distance()}`;
}
}
An interface defines the structure of an object. Interfaces contain property names and types but don't contain implementation.
interface User {
name: string;
id: number;
}
function printUser(user: User) {
console.log(`${user.name} - ${user.id}`);
}
let user = {name: "Bob", id: 1};
printUser(user);
Interfaces can also describe function types.
interface SearchFunc {
(source: string, query: string): boolean;
}
let search: SearchFunc;
search = function(src, qry) {
// Search implementation
}
Generics provide parametrised types. The type parameters are specified inside angle brackets.
This allows code to be written flexibly while retaining type safety.
function firstElement<T>(arr: T[]): T {
return arr[0];
}
let num = firstElement([1, 2, 3]); // num is inferred as number
let str = firstElement(["a", "b"]); // str is inferred as string
TypeScript provides excellent tooling support including:
tsc
to transpile to JavaScriptTypeScript has great integration with JSX and React with the react
and react-dom
type declarations.
Popular frameworks like Angular come with TypeScript support built-in.
The key aspects of coding in TypeScript include:
TypeScript makes it easy to write scalable apps with a familiar syntax. The optional types bring more robustness and prevent bugs. Definitely consider using TypeScript for your next JavaScript project!
TypeScript offers benefits like early error catching, easy refactoring with IDE support, and better auto-complete and documentation. It makes large JavaScript codebases more manageable and less bug-prone.
No, TypeScript compiles to plain JavaScript so it augments rather than replaces JavaScript. The emitted JavaScript can run wherever standard JavaScript runs.
Yes, TypeScript usage is growing rapidly and can be a valuable skill. Understanding TypeScript improves your general programming abilities. TypeScript roles are in high demand.
No, TypeScript can bring benefits to projects of all sizes. Even individual .ts files can utilise types. Scaling up is easier with TypeScript already in place.
All major code editors like VS Code, WebStorm, Atom, Sublime, and Vim provide excellent support for TypeScript.
This article is part of an ongoing series in Typescript you might like to read our article on How to migrate from JavaScript to Typescript
CONTACT
+44 (0)20 8446 7555
Copyright © 2024 JBI Training. All Rights Reserved.
JB International Training Ltd - Company Registration Number: 08458005
Registered Address: Wohl Enterprise Hub, 2B Redbourne Avenue, London, N3 2BS
Modern Slavery Statement & Corporate Policies | Terms & Conditions | Contact Us