MAL's Logo

TypeScript - Basic Concepts

💡 Tips and tricks to get started with TypeScript.

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 array

Tuples 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;
}

Extras

  • anotherData: any; - here, typescript says, "i give up, i can't check this"
  • type void, is the absence of having no type at all, often used as the return type of functions that don’t return a value
  • in some occasions, you know more about a value than TS does, which is where type assertions come in: name as string is how to get around it
  • remember all types should be written in lowercase
  • Resources

  • https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html
  • https://www.typescriptlang.org/docs/handbook/basic-types.html
  • MAL's Logo© 2021 – 2026 MAL. All rights reserved.