Skip to content

Common Types

Video Lecture

Section Video Links
Let/Const Let/Const Let/Const 
Types Types Types 
Strings Strings Strings 
Boolean Boolean Boolean 
Number Number Number 
Array Array Array 
Dictionary Dictionary Dictionary 
Tuple Tuple Tuple 
Set Set Set 

Overview

This section is a basic introduction of the types that you can use in TypeScript. It is useful to help you learn some TypeScript basics in case you are new to TypeScript. Each of the types listed below are used throughout the patterns.

Let/Const

When declaring any properties in your TypeScript files, you can declare them using the let or const keywords.

If you declare a property using let, e.g.,

let a = 1

then you can change the value of a at a later time.

let a = 1
a = 2

If you declared a as a const, then you wouldn't be able to change a later. It will stay as a constant value throughout the lifetime of your program.

const a = 1
a = 2

Changing the value of a would indicate an error.

When you declare a const, you must also initialize it with a value at the same time. E.g.,

const a = 1

If you declared it as just,

const a

Then that would indicate an error that const declarations must be initialized with a value.

You can also use the var keyword to create properties/variables. But it is better practice using either let or const since they will be treated as block scope variables when declared within classes or any other code within curly braces {}, rather than global. Variables declared using the var keyword may overwrite variables of the same name that are used elsewhere in your program. When using let or const, TSC errors and warnings will also be much more relevant. If you were to use a linter on your code, such as ESLint, and it found usages of var then you would see the error,

Unexpected var, use let or const instead

Types

Replace ./src/test.ts with this script below and recompile using tsc -p ./src

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
let foo: string
let bar: boolean
let baz: number
let qux: string[]
let quuz: [number, string]
let corge: { [key: number]: string }
let grault: Set<number>

foo = 'ABC'
bar = true
baz = 123
qux = ['a', 'b', 'c']
quuz = [1, 'abc']
corge = { 123: 'abc', 456: 'def' }
grault = new Set([1, 2, 3])

Open the compiled JavaScript version from ./dist/test.js in the editor.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
'use strict'
let foo
let bar
let baz
let qux
let quuz
let corge
let grault
foo = 'ABC'
bar = true
baz = 123
qux = ['a', 'b', 'c']
quuz = [1, 'abc']
corge = { 123: 'abc', 456: 'def' }
grault = new Set([1, 2, 3])

You can see that the compiled JavaScript is almost identical. While in the TypeScript version, the types are explicit and must conform when the variables are assigned vales, the JavaScript version does not indicate the type, but will fall back to a type known as any which can be anything. Since the source was written in TypeScript, you can trust that the outputted JavaScript will work correctly in regard to the types that you have chosen despite the JavaScript version not actually enforcing it.

So, in the TypeScript version I have demonstrated explicitly setting some types of

  • string
  • boolean
  • number
  • array of numbers
  • a tuple of two elements consisting of a number and a string
  • dictionary if string where the key is a number
  • a Set of numbers

As an experiment, try swapping some types of each variable without changing the values. I.e., re-declare foo as a boolean and you will see that the VSCode IDE will indicate that you are assigning the wrong type of values to each variable. If you were to write this directly in JavaScript, then no such error would be indicated.

Strings

Some more string experiments you can try are,

1
2
3
4
5
6
let foo: string
foo = 'ABC'
foo = '123'
foo = 'ABC = 123'
foo = 'quick brown fox, etc'
foo = "It wasn't me"

It is common practice, but not essential, to wrap single quotes around string values unless it contains a single quote in it, e.g., "didn't".

Boolean

A boolean can either be true or false.

1
2
3
let bar: boolean
bar = true
bar = false

Number

A number can be written in many bases or with floating point precision.

1
2
3
4
5
6
let baz: number
baz = 123 //decimal
baz = 123.456 //float
baz = 0xffff //hex
baz = 0b10101 //binary
baz = 0o671 //octal

Array

An array is a JavaScript object first that can contain a series of any types, but in TypeScript you can set the types explicitly or even as unknown.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
let a: string[]
a = ['a', 'b', 'd', 'd']
let b: number[]
b = [1, 2, 3, 4]
let c: boolean[]
c = [true, false, true]
let d: unknown[]
d = [1, 'a', true, ['even', 'another', 'internal', 'array']]

// Array items can be retrieved using a zero based index.
console.log(a[1])
console.log(b[0])
console.log(c[1])
console.log(d[2])

Outputs

b
1
false
true

Some other operations on an Array.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
const a = ['a', 'b', 'c', 'd']

// log the whole array
console.log(a)

// log how may items in the array
console.log(a.length)

// returns and removes the last item from the array
console.log(a.pop())

// returns and removes the first item from the array
console.log(a.shift())

// log the whole array again
console.log(a)

// add an item to the end
a.push('z')
console.log(a)

// add an item to the beginning
a.unshift('x')
console.log(a)

// remove 1 item starting at the 3rd item (0 based index)
a.splice(2, 1)
console.log(a)

// replace an item (0 based index)
a[1] = 'y'
console.log(a)

Outputs

[ 'a', 'b', 'c', 'd' ]
4
d
a
[ 'b', 'c' ]
[ 'b', 'c', 'z' ]
[ 'x', 'b', 'c', 'z' ]
[ 'x', 'b', 'z' ]
[ 'x', 'y', 'z' ]

I have used Arrays in various other ways in almost every single pattern example in the course.

Visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array for more detailed information about the Array.

Dictionary

A Dictionary is used as a key/value construct, where you can retrieve a value from the dictionary by using a key.

1
2
3
4
5
6
7
let a: { [key: number]: string }
a = { 123: 'abc', 456: 'def' }
let b: { [key: string]: boolean }
b = { abc: true, def: false, ghi: true }

console.log(a[123])
console.log(b['def'])

Outputs

abc
false

Some other operations on a Dictionary.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// The key of a dictionary can be of any type and name
let a: { [key: string]: string }
let b: { [id: number]: string }
a = { a: 'car', b: 'train', c: 'plane', d: 'boat' }
b = { 1: 'car', 2: 'train', 3: 'plane', 4: 'boat' }
// and can be retrieved as such
console.log(a['a'])
console.log(b[2])

// Since Dictionaries are really just objects. You can also retrieve
// a dictionary's value using object notation if the keys are strings
console.log(a.c)
// console.log(b.2) // this doesn't work when the key is a number

// you can add items to a dictionary
a['e'] = 'go-cart'
console.log(a)

// you can delete
delete b[2]
console.log(b)

// The values of a dictionary can be of any type, even an array.
let c: { [id: number]: number[] }
c = { 1: [1, 2, 3], 2: [4, 5, 6], 3: [7, 8, 9], 4: [10, 11, 12] }
console.log(c)

Outputs

car
train
plane
{ a: 'car', b: 'train', c: 'plane', d: 'boat', e: 'go-cart' }
{ '1': 'car', '3': 'plane', '4': 'boat' }
{
  '1': [ 1, 2, 3 ],
  '2': [ 4, 5, 6 ],
  '3': [ 7, 8, 9 ],
  '4': [ 10, 11, 12 ]
}

The Dictionary is actually a basic object {} in JavaScript. But in TypeScript, we can also set the types of the keys and values.

I have used Dictionaries in various other ways in the Command, Facade, Flyweight, Observer and Singleton pattern examples.

Tuple

The Tuple is similar to an array, but you are explicitly indicating how many items are in the Tuple and of which type they are when you instantiate it. The Tuple type is not directly supported in JavaScript as a Tuple, but as an array instead. The rules of the Tuple are enforced in TypeScript only when it is created. After the Tuple is created, it behaves the same as an array. You can add/remove/edit items.

1
2
3
4
5
6
7
let a: [number, string]
a = [1, 'abc']
let b: [string, boolean, number]
b = ['abc', false, 123]

console.log(a[1])
console.log(b[2])

Outputs

abc
123

I have used Tuples in various other ways in the pattern examples for the Adapter and Facade (as the getHistory dictionary values).

Set

The Set object lets you store unique values of any type. Any duplicate items added to the Set won't be added.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let a: Set<number>
a = new Set([1, 2, 3, 4])
let b: Set<string>
b = new Set(['a', 'b', 'c', 'd', 'a']) // the second `a` is not added
let c: Set<unknown>
c = new Set([1, 'b', true])

console.log(a)
console.log(b)
console.log(c)

Outputs

Set(4) { 1, 2, 3, 4 }
Set(4) { 'a', 'b', 'c', 'd' }
Set(3) { 1, 'b', true }

Some other operations on a Set.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const a: Set<string> = new Set()
// adding items
a.add('cat')
a.add('dog')
a.add('bird')
console.log(a)

// remove an item
a.delete('dog')
console.log(a)

// Retrieve an individual item.
console.log(Array.from(a)[1])

// The great thin about a set compared to an array, is that all
// items are guaranteed to be unique. No duplicates allowed.
a.add('bird')
a.add('bird')
console.log(a)

// Get the length of the Set
console.log(a.size)

// Check if a Set has a value
console.log(a.has('cat'))

Outputs

Set(3) { 'cat', 'dog', 'bird' }
Set(2) { 'cat', 'bird' }
bird
Set(2) { 'cat', 'bird' }
2
true

Sets are a JavaScript concept first, but the types within the Set can be assigned using TypeScript.

I have used Sets in various other ways in the Mediator, Memento and Observer pattern examples.


Note that this course does not cover all the types and all the many features that can be found when using TypeScript. You can visit https://www.typescriptlang.org/docs/handbook/2/everyday-types.html for a more detailed explanation of each type and also many more of types if you want to explore them further.