Skip to content

Instantly share code, notes, and snippets.

@jkirira
Last active July 20, 2025 15:37
Show Gist options
  • Select an option

  • Save jkirira/d1aa10c9e40a3718e1970607e3867d5f to your computer and use it in GitHub Desktop.

Select an option

Save jkirira/d1aa10c9e40a3718e1970607e3867d5f to your computer and use it in GitHub Desktop.

Add types when declaring or initializing.

let username: string = "jkirira"
let username: string;

Basic Types

let id: number = 5
let company: string = 'Traversy Media'
let isPublished: boolean = true
let x: any = 'Hello'

arrays

let ids: number[] = [1, 2, 3, 4, 5]
let arr: any[] = [1, true, 'Hello']
let stringOrNumberArray: (string | number)[];

Tuple

let person: [number, string, boolean] = [1, 'Brad', true]

Array of Tuples

let employees: [number, string][]
employees = [
  [1, 'Brad'],
  [2, 'John'],
  [3, 'Jill'],
]

Union

let pid: string | number
pid = '22'

Enum

enum Direction1 {
  Up = 1,
  Down,
  Left,
  Right,
}

enum Direction2 {
  Up = 'Up',
  Down = 'Down',
  Left = 'Left',
  Right = 'Right',
}

Objects

type User = {
  id: number
  name: string
}

const user: User = { id: 1, name: 'John' }

Functions: (parameters and return value(s));

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

const add = (x: number, y: number): number => x + y

Generics

functions createPair<T, K>(input1: T, input2: K): [T, K] => {
  return [input1, input2];
}

const createArrayPair = <T, K>(input1: T, input2: K): [T, K] => [input1, input2]

Notes

Dont have to add types when calling a function or initializing as the return value of a function

Only add types when calling a function if you are using generics e.g. useState<String | null>(null);

For react hooks that start off as null use generics e.g. const [username, setUsername] = useState<String | null>(null);


const buttonTextOptions = [
  "Click me!",
  "Click me again!",
  "Click me one more time!"
] as const;

const buttonTextOptions = "Click me!" | "Click me again!" | "Click me one more time!";

type User = {
  sessionId: "string";
  name: "string"
}

type Guest = Omit<User, "name">;

{ theme as React.ReactNode }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment