Logo

SudoVersity

SudoMistress
May 10, 2023 Updated: Apr 17, 2024

TypeScript Basics

Just a quick post for helping to remember TypeScript syntax. This is not an explanation, a tutorial, or guidance. For that see the section below called Resources.

Primatives

CODE
// String
let myName: string = 'Josey'
// Number
let favNumber: number = 13
// Boolean
let isCool: boolean = false
// Array
let favAnimals: string[] = ['cat', 'dog', 'all']

Parameters

CODE
// Typical
function printToConsole(eventNumber: number, eventMessage: string) {
	console.log(`LOG: ${eventNumber}: ${eventMessage}`)
}

Objects

NOTE

There are multiple ways to annotate an object. Each has an impact.

Inline

Pass object type directly or inline: gives verbose error that includes full object type.

CODE
export const multiplyTwoNumbers = (params: { first: number; second: number }) => {
	return params.first * params.second
}

Type

Named Type: represents anything from an object, to string, number, or boolean.

CODE
type MultiplyTwoNumbers = {
	first: number
	second: number
}

export const multiplyTwoNumbers = (params: MultiplyTwoNumbers) => {
	return params.first * params.second
}

Interface

Named Interface: Works with ojbects only for the most part.

CODE
interface MultiplyTwoNumbers {
	first: number
	second: number
}

export const multiplyTwoNumbers = (params: MultiplyTwoNumbers) => {
	return params.first * params.second
}

Optional

The ? character makes a property or parameter optional. This means the property or parameter or object that is using the declared type.

CODE
interface MultiplyTwoNumbers {
	first: number
	second?: number
}

Using type | undefined where type is a primative can be used to ensure the value of that specific key/value pair do not need a value, but the key must still be sent and declared as undefined in that case.

CODE
type MultiplyNumbers = {
	first: number
	second: number
	third: number | undefined
}

export const multiplyTwoNumbers = (params: MultiplyNumbers) => {
	return params.first * params.second
}

multiplyTwoNumbers({ first: 5, second: 16, third: undefined })

Variable Interface Assigning

CODE
interface Animal {
	id: number
	name: string
	legs: number
}

const newAnimal: Animal = {
	id: 334,
	name: 'Agnes',
	legs: 4,
}

Union Types (Value Type Contraints)

CODE
interface Animal {
	id: number
	name: string
	legs: 2 | 3 | 4
}

Arrays, Combining Types

CODE
interface Animal {
	id: number
	name: string
	legs: 2 | 3 | 4
	owners: Owner[]
}

interface Owner {
	id: number
	firstName: string
	lastName: string
}

const newAnimal: Animal = {
	id: 334,
	name: 'Agnes',
	legs: 4,
	owners: [
		{
			id: 13,
			firstName: 'Josey',
			lastName: 'Howarth',
		},
		{
			id: 69,
			firstName: 'Dan',
			lastName: 'Howarth',
		},
	],
}

Typing Function Returns

CODE
const makeAnimal = (): Animal => {
	return {
		id: 334,
		name: 'Agnes',
		legs: 4,
		owners: [
			{
				id: 13,
				firstName: 'Josey',
				lastName: 'Howarth',
			},
			{
				id: 69,
				firstName: 'Dan',
				lastName: 'Howarth',
			},
		],
	}
}

Promises

There are mutliple ways to do this.

CODE
interface Animal {
  id: number;
  name: string;
  legs: 2 | 3 | 4;
}

// Promise Method

export const fetchAgnes = async (): Promise<Animal> => {
    const data = await fetch("https://www.reallycoolapifakeaddress.com/api/animal/334").then((res)) => {
        return res.json();
    });
    return data;
};

// Recommended methods for working with fetch
// Typing fetched response
export const fetchAgnes = async () => {
    const data: Animal = await fetch("https://www.reallycoolapifakeaddress.com/api/animal/334").then((res)) => {
        return res.json();
    });
    return data;
};

// Casting (assigning is safer than using casting)
export const fetchAgnes = async () => {
    const data = await fetch("https://www.reallycoolapifakeaddress.com/api/animal/334").then((res)) => {
        return res.json();
    });
    return data as Animal;
};

TypeScript Comments

CODE
// @ts-expect-error
/// Tells TS that an error should show on the next line

// @ts-ignore
/// Tells TS to ignore the next line

Resources

If you’re wanting to dig deeper into the concepts of TypeScript, I cannot recommend the following two resources enough.

  1. Total Typescript
  2. TypeScript Handbook