TypeScript Fundamentals - Basic Types
TypeScript being a superset of JavaScript has all the types of JavaScript including its own types. In this post, we will be looking at all the types available in TypeScript and how they are defined and used effectively. I will also be giving tips on how to avoid common mistakes when using TypeScript in your own programs.
Boolean
The Boolean type is similar to the Boolean type of any other language and has two possible values, true
and false
.
const isOdd: boolean = true;
const isEven: boolean = false;
Number
All numbers in TypeScript are floating point values and it supports multiple literals for numbers such as hexadecimals, binary, octal, and more.
const fibonacci: number = 34; //decimal
const color: number = 0xbada55; //hexadecimal
const adder: number = 0b1011; //binary
const chmod: number = 0o755; //octal
String
Both double quotes (”) and single quotes (’) are supported to surround string data in TypeScript. Also template strings are supported with string interpolation using expressions of the form ${ expression }
.
The expression can be any valid JavaScript expression.
const firstName: string = 'John';
const lastName: string = 'Smith';
const fullName: string = `${firstName} ${lastName}`; // John Smith
Array
Arrays in TypeScript work the same as in JavaScript and can be written in two ways. The first way to write arrays is using the brackets notation and the second way is to use the Generics notation (we will look at Generics later).
const fibonacci: number[] = [0, 1, 1, 2, 3, 5, 8, 13, 21, 34];
const faang: Array<String> = [
'Facebook',
'Amazon',
'Apple',
'Netflix',
'Google',
];
Tuple
This type stores a fixed number of elements in an array whose types are known. Since the array size is fixed, we can use their index within the Tuple to get their values.
let streetName: [number, string] = [322, 'HighWay Dr.'];
console.log(streetName[0]); // 322
console.log(streetName[1]); // HighWay Dr.
streetName = ['HighWay Dr.', 322]; // Error
Enum
An enum gives friendly names to sets of numeric values. Enums start their numbering at 0, and you can change it to start from a different number by specifying that number for the first element.
We can also go from the enum index to the string value.
enum StateTrinity {
Loading,
Success,
Error,
}
const ajaxCall: StateTrinity = StateTrinity.Success;
const enumName: string = StateTrinity[2];
console.log(enumName); // Displays 'Error'
Any
When we have a variable that we don’t know its type yet, we can assign it the any
type to make TypeScript compile. This is useful when you start refactoring a previous JavaScript codebase and need to have placeholder types while you do the conversion, or when you have data coming from a third party that is not typed.
However, try not to use the any
type as it defeats the purpose of using TypeScript.
let ajaxResponse: any = { x: 20, y: 30, z: 40 };
ajaxResponse = 'This is an error';
ajaxResponse = true;
In JavaScript arrays are not typed, hence arrays can contain any type. To do the same in TypeScript, we can define our array type to be any
.
const random: any[] = ['House', 24, 'Roof', { x: 1, y: 2 }];
Void
Void is a type used in the absence of any type. Commonly used for functions that do not return a value, such as functions which use console.log
for their side effects.
It is not useful to declare variables with type void
because you can only assign null
or undefined
to them. If the compile option of --strictNullChecks
is used, then you cannot assign null
to a void
variable.
function logOutput(): void {
const message: string = receiveValueFromApi();
console.log(message);
}
Null and Undefined
Unlike JavaScript, null
and undefined
are their own types in TypeScript and are subtypes of all other types. That means without using the compile option --strictNullChecks
, you can assign null or undefined to a variable with type such as number
or string
. To avoid common mistakes, use the --strictNullChecks
compile option and then use union types if you want to accept null with your other types.
let salary: number | null = 345000;
salary = null; // This is valid because null is part of the type.
Never
A function that throws an error or never returns gets its returned type inferred as never
. If you have a function that produces an infinite loop and never reaches an end point, then its type is inferred to be never
.
// Inferred return type is never
function divideByZero(num: number) {
throw new Error('We cannot divide by zero');
}
Object
The object
type is used for any type that is not a primitive type (number, string, boolean, etc).
We can declare a function that takes an object or null and calling the function with a primitive type will fail.
function parseObject(obj: object | null): void {
console.log(obj);
}
parseObject({ x: 10, y: 20, z: 30 }); // OK
parseObject(null); // OK
parseObject(322); // Error
parseObject(true); // Error
The above types cover all the basic types in TypeScript and can be used to compose complex types for other purposes. Just from learning these types, you can start to understand TypeScript code and see the semantics of their definitions. Of course there is more to learn which we will be covering next.