ruk·si

🏷️ TypeScript
Basics

Updated at 2024-04-14 11:57

Basic types:

const isDone: boolean = false;
const decimal: number = 6;
const name: string = 'John Doe';
const sentence: string = `Hello, my name is ${fullName}.`;

Arrays:

const numbers: number[] = [1, 2, 3];
const words: Array<string> = ['apple', 'car', 'cat'];

Special types:

// `any` can contain a value of any type
let notSure: any = 4;

// `void` is the opposite of `any`, absence of a value
// only undefined and null match to void
function log(): void {
    console.log('hello world');
}

// `never` represents values that never occur
// e.g. functions that always throw an exception or never return
function error(msg: string): never {
    throw new Error(msg);
}

Type assertions:

const someValue: any = "this is a string";
const strLength1: number = (<string>someValue).length;
const strLength2: number = (someValue as string).length;

Type assertions are not checked at run-time, so you need to add type guards.

var shape = createShape();
if (shape instanceof Circle) {
    var circle = <Circle>shape;
}

Prefer named functions over unnamed functions. They keep track of their name for easier debugging, and functions are hoisted so order of their definition is not as strict.

function namedAdd(x: number, y: number): number {
    return x + y;
}

const anonymousAdd = function (x: number, y: number): number {
    return x + y;
}

All function parameters are required by default, but you can use ? to make them optional. The same is true for object properties.

constructor(id ? : string)
:
void {
    console.log(id)
}

interface TodoState {
    isEditing?: boolean
}

! tells the compiler that something cannot be null or undefined in the given context.

// ! tells the compiler that something cannot be null/undefined
project!.name

?? is the nullish coalescing operator, it returns the right-hand operand when the left-hand operand is null or undefined.

const foo = null ?? 'default string';

?. is the optional chaining operator, it allows you to access deeply nested properties without worrying about whether the property exists or not.

const foo = bar?.baz?.qux;

Sources

  • Learning TypeScript by Josh Goldberg