Published on

Basic intro to Typescript for beginners

Authors
  • avatar
    Name
    Mansour Mahamat-salle
    Twitter
    @Mans_JS
row

TypeScript has become increasingly popular over the last few years, and many jobs are now requiring developers to know TypeScript. TypeScript is a superset of JavaScript that extends the language by adding types and other functionalities. Don't panic – if you already know JavaScript, you will be able master TypeScript quickly.

Bugs in programming are just unavoidable, TypeScript can prevent a LOT of bugs! in adding static typing to JavaScript

You can start using TypeScript in the browser: TypeScript playground

Primitive types

In JavaScript, a primitive value is data that is not an object and has no methods. There are 7 primitive data types:

  • string
  • number
  • bigint
  • boolean
  • undefined
  • null
  • symbol

Variables

TypeScript use colon ":" to assign a type to a variable.

let color: string = 'blue'
let age: number = 55
let isLogged: boolean = false

If you try to set a string value to age you will get an error and this is a benefit of using TypeScript

 age = "55" // Error: Type 'string' is not assignable to
type 'number'.

Union types

A variable can have multiple types. This concept is called Union in TypeScript. Use the pipe character to define multiple types:

let id: string | number
id = 'id23456'
id = 9889876

Arrays

In TypeScript, you can define what type of data an array can contain:

let postal: number[] = [987, 562, 3678, 4554, 335]; // can only contain numbers
let city: string[] = ['Paris', 'Milan', 'Dakar']; // can only contain strings
let options: boolean[] = [true, false, false]; can only contain true or false

We can use union types too

let player: (string | number | boolean)[] = ['Neymar', 10, true]

Tuples

A tuple is an array with fixed size and known datatypes. They are stricter than regular arrays, you can declare a new variable composed for 2 or more values

const player: [string, string] = ['Zidane', 'Riquelme']

You can create an array of tuples

const player: [number, string][]

player = [
  [1, 'Figo'],
  [2, 'Deco'],
  [3, 'Felix'],
]

Types

In TypeScript you can create types by adding properties names and types.

type Player = {
  id: number
  name: string
  lastName: string
  position?: string //with the question mark you set undefined as a possible value
}

const newPlayer: Player = { id: 1, name: 'Messi', lastName: 'Lionel' }

We can do the same with function

const printFullName = ({ name, lastName }: Player) => {
  console.log(`My fullname is ${name} ${lastName}`)
}
printFullName(newPlayer)

Generics

Generics allow you to create a component that can work over a variety of types, rather than a single one, which helps to make the component more reusable.

function MyType<T>(value: T): string {
  return typeof value
}

//when you call the function you can specify the type that you want to use
console.log(MyType<number>(100))
console.log(MyType<boolean>(true))
console.log(MyType<string>('string value'))

You can also extend using generics to include a specific property by default in the type

interface HasId {
  id: number
}

class Item implements HasId {
  constructor(public id: number) {}
}

class GenericModel<T extends HasId> {
  items: T[] | undefined

  constructor(public name: string) {}

  getItembyId(id: number) {
    return this.items?.find((p) => p.id === id)
  }
}

Interfaces

Interfaces define how an object should look:

interface Person {
  name: string
  age: number
}

function sayHi(person: Person) {
  console.log(`Hi ${person.name}`)
}

sayHi({
  name: 'Tony',
  age: 48,
}) // Hi Tony

Interface vs Type

  • Interfaces represent the object data structure
  • Type is an alias to represent primitive types and objects like data structure
  • Both are fine, but interfaces are more common and more strict
  • Type could have a primitive value interface not:
type Player =
  | string
  | {
      id: number
      name: string
      lastName: string
      number?: string //with the question mark you set undefined as a possible value
    }

Literal types

In addition to the general types string and number, we can refer to specific strings and numbers in type positions:

let favouritePlayer: 'Ronaldo' | 'Zidane' | 'Ronaldinho' | 'Henry'

favouritePlayer = 'Ronaldo'
favouritePlayer = 'Thuram' // ERROR: Type '"Thuram"' is not assignable to type Ronaldo' | 'Zidane' | 'Ronaldinho' | 'Henry'.

Enums

An enum can be defined using the enum keyword. Enums allow us to define or declare a collection of related values, that can be numbers or strings, as a set of named constants

enum Direction {
  Up = 1,
  Down,
  Left,
  Right,
}

All of the following members are auto-incremented from that point on. In other words, Direction.Up has the value 1, Down has 2, Left has 3, and Right has 4.

It was a basic intro to Typescript, now you are ready to start a project with TypeScript and learn advanced topics.