CUSTOMISED
Expert-led training for your team
Dismiss
How to code in Typescript

21 August 2023

How to Code in TypeScript

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. 

Introduction to TypeScript

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.

Basic Syntax

The basic syntax of TypeScript is very similar to JavaScript. Let's look at some examples.

Variables

Variables can be declared with let and const. Type annotations are optional.

let name: string = "Alice";

const age: number = 25; 

Functions

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;
}

Objects

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

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

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.

Classes

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()}`;
  }

}

Interfaces

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

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  

Tooling

TypeScript provides excellent tooling support including:

  • Compilers like tsc to transpile to JavaScript
  • Linters like ESLint to catch errors and enforce style
  • Formatters like Prettier for code consistency
  • Testing frameworks like Jest with additional TypeScript support

TypeScript 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.

Conclusion

The key aspects of coding in TypeScript include:

  • Optional static type annotations
  • Traditional object-oriented classes
  • Interfaces to define contracts
  • Generics for parameterized types
  • Excellent tooling and editor support

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!

Frequently Asked Questions

What are the benefits of TypeScript?

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.

Does TypeScript replace JavaScript?

No, TypeScript compiles to plain JavaScript so it augments rather than replaces JavaScript. The emitted JavaScript can run wherever standard JavaScript runs.

Is TypeScript worth learning?

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.

Is TypeScript only for large projects?

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.

What code editors support TypeScript?

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

About the author: Daniel West
Tech Blogger & Researcher for JBI Training

CONTACT
+44 (0)20 8446 7555

[email protected]

SHARE

 

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

POPULAR

Rust training course                                                                          React training course

Threat modelling training course   Python for data analysts training course

Power BI training course                                   Machine Learning training course

Spring Boot Microservices training course              Terraform training course

Kubernetes training course                                                            C++ training course

Power Automate training course                               Clean Code training course