Working with Types in TypeScript
Core Syntax and Features
Core Types
TypeScript introduces several basic types to help catch errors during development. These types include:
number: Represents all numbers (no distinction between integers and floats).
string: Represents all text values.
boolean: Represents
true
andfalse
.
Note: TypeScript's type system only helps during development, before the code gets compiled.
Example Code:
function add(num1: number, num2: number) {
return num1 + num2;
}
const num1 = '5';
const num2 = 2.8;
const result = add(num1, num2);
console.log(result);
In this example, TypeScript will show a warning on num1
because it is a string, while the add
function expects numbers. If we compile this code, we will get an error.
Correcting the Error:
To fix this, we need to ensure num1
is a number:
function add(num1: number, num2: number) {
return num1 + num2;
}
const num1 = 5;
const num2 = 2.8;
const printResult = true;
const result = add(num1, num2);
console.log(result);
Adding More Parameters:
If we want to pass an additional parameter, we need to update the function definition:
function add(num1: number, num2: number, printResult: boolean) {
if (printResult) {
console.log(num1 + num2);
}
return num1 + num2;
}
const num1 = 5;
const num2 = 2.8;
const printResult = true;
const result = add(num1, num2, printResult);
Now, everything works fine. If we hover over num1
, we see its type is number
. If we try to reassign it with a string:
let num1 = 5;
num1 = '5';
TypeScript will show a warning because num1
is initially defined as a number
.
Core Types Continued:
Objects
const person = {
name: 'Sufiyan',
age: 33
};
console.log(person.nickname);
TypeScript will warn that nickname
does not exist on the person
object. If you hover over person
, you'll see its inferred types:
const person: {
name: string;
age: number;
}
You can explicitly define these types:
const person: {
name: string;
age: number;
} = {
name: 'Sufiyan',
age: 33
};
Arrays
const person = {
name: 'Sufiyan',
age: 33,
hobbies: ['Teaching', 'Learning']
};
Here, hobbies
has the type string[]
(array of strings).
You can also define array types before initialization:
let sports: string[];
Assigning a non-array value will result in an error:
sports = 'sports'; // Error
Assigning an array with mixed types also causes an error:
sports = ['cricket', 1]; // Error
Instead, use any[]
for mixed types:
let sports: any[];
However, using any
is generally discouraged.
Tuples
A tuple is a fixed-length array with specified types for each element:
const person = {
name: 'Sufiyan',
age: 33,
hobbies: ['Teaching', 'Learning'],
role: [2, 'author']
};
// Type: (number | string)[]
Updating tuple elements correctly:
person.role[1] = 'admin'; // No error
person.role = [1, 'author', 'teacher']; // Error
Using push
is allowed but not recommended for tuples.
Enums
Enums define a set of named constants:
enum Role { ADMIN, READ_ONLY, AUTHOR }
const person = {
name: 'Sufiyan',
age: 33,
hobbies: ['Teaching', 'Learning'],
role: Role.ADMIN
};
By default, enum values start from 0
. You can customize these values:
enum Role { ADMIN = 5, READ_ONLY = 100, AUTHOR = 200 }
Enums can also have mixed types:
enum Role { ADMIN = 'ADMIN', READ_ONLY = 100, AUTHOR = 'AUTHOR' }
Any
The any
type allows any kind of value, disabling type checking:
let randomValue: any = 'Hello';
randomValue = 5; // No error
Using any
should be minimized to retain the benefits of TypeScript.