TypeScript - Basic Concepts
Breakdown
1. Basic types
The basic datatypes are types commonly known from JavaScript and the likes.
const isLoading: boolean = false;
const myNumber: number = 1;
const myString: string = "John";
const list: Array<string> = ["Apples", "Oranges", "Bananas"];
const list: string[] = ["Apples", "Oranges", "Bananas"];
const results: number[] = [39, 22, 40];2. Enum and Tuple
Enums can be numeric and string values, allowing us to declare a set of named constants.
enum Role { ADMIN, DEV, EDITOR };
// ps. enum assigns numbers to labels, starting from 0 like an arrayTuples allow you to declare an array with a fixed number of elements.
const person: {
name: string;
age: number;
role: [number, string]; // tuple, aka, fixed-length array
} = {
name: 'Max',
age: 30
role: [2, 'author']
role: Role.ADMIN // how to use enum
};3. Unknown
In a rare occasion where we’re unaware of a variable’s type, it is recommended to use unknown over any. Unlike the latter, the former offers type-checking.
What does it mean? If we use any, we are telling TypeScript to back off. By using unknown, however, no operations will be permitted until we assert it to a specific type.
let userInput: unknown;
const userName = "cheers";
if (typeof userInput === 'string') {
userInput = userName;
}