askesis

TypeScript flashcards: 50 essentials with code

Learn the TypeScript you use every day: narrowing, generics, keyof, mapped and conditional types, utility types, satisfies and strict mode, with code on every card.

ProgrammingIntermediate50 cardsFree

Practice now

Study without an account

0 of 50 seen0 graduated
type vs interface

Scheduled with the default Askesis timings. Progress is saved in this browser.

All 50 cards

  1. 1
    type vs interface
    Both describe object shapes; interfaces can be reopened and merged, type aliases can also name unions, tuples, primitives and mapped types
  2. 2
    What is declaration merging?
    Two interface declarations with the same name merge into one with all members
    ts
    interface User { id: string }
    interface User { name: string }
    const u: User = { id: '1', name: 'Ada' }
  3. 3
    What can you do with a value of type string | number before narrowing?
    Only what both members support (e.g. toString())
  4. 4
    Narrow a union with typeof
    ts
    function format(v: string | number) {
      if (typeof v === 'number') return v.toFixed(2)
      return v.trim() // v is string here
    }
  5. 5
    Narrow with the in operator
    ts
    function move(a: Fish | Bird) {
      if ('swim' in a) a.swim()
      else a.fly()
    }
  6. 6
    What is a discriminated union?
    A union whose members share a literal property (like kind) that narrows the type when checked
    ts
    type Shape =
      | { kind: 'circle'; r: number }
      | { kind: 'square'; size: number }
    
    function area(s: Shape) {
      if (s.kind === 'circle') return Math.PI * s.r ** 2
      return s.size ** 2
    }
  7. 7
    How do you make a switch over a union exhaustive?
    Assign the value to never in the default branch; a new, unhandled member becomes a compile error
    ts
    default: {
      const unreachable: never = s
      throw new Error(`Unhandled: ${unreachable}`)
    }
  8. 8
    unknown vs any
    any switches type checking off; unknown accepts anything but must be narrowed before use
  9. 9
    What is the never type?
    The type with no values: functions that always throw, impossible branches, the empty union
  10. 10
    Can a () => void callback type accept a function that returns a value?
    Yes. void there means the return value is ignored, so arr.forEach(x => list.push(x)) type-checks
  11. 11
    Write a user-defined type guard
    ts
    function isString(x: unknown): x is string {
      return typeof x === 'string'
    }
  12. 12
    Write an assertion function
    ts
    function assert(cond: unknown, msg?: string): asserts cond {
      if (!cond) throw new Error(msg)
    }
    Declare it with function or an explicitly typed const; TypeScript rejects calls through an unannotated arrow.
  13. 13
    A generic function returning the first element
    ts
    function first<T>(items: T[]): T | undefined {
      return items[0]
    }
  14. 14
    Constrain a type parameter
    ts
    function longest<T extends { length: number }>(a: T, b: T): T {
      return a.length >= b.length ? a : b
    }
  15. 15
    What does keyof produce?
    A union of an object type’s keys
    ts
    type K = keyof { a: 1; b: 2 } // 'a' | 'b'
  16. 16
    typeof in a type position
    The type of a value
    ts
    const config = { port: 3000, host: "localhost" }
    type Config = typeof config // { port: number; host: string }
  17. 17
    What is an indexed access type?
    Looking up a property’s type by key, like Config["port"]; T[number] gives an array’s element type
  18. 18
    Type a safe property getter
    ts
    function get<T, K extends keyof T>(obj: T, key: K): T[K] {
      return obj[key]
    }
  19. 19
    What is a mapped type?
    A type built by iterating over keys
    ts
    type Flags<T> = { [K in keyof T]: boolean }
  20. 20
    Remove readonly and ? in a mapped type
    Prefix the modifier with -
    ts
    type Concrete<T> = { -readonly [K in keyof T]-?: T[K] }
  21. 21
    Rename keys in a mapped type
    Use an as clause
    ts
    type Getters<T> = {
      [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K]
    }
  22. 22
    Conditional type syntax
    ts
    type IsString<T> = T extends string ? true : false
  23. 23
    What is IsString<string | number> if IsString<T> = T extends string ? true : false?
    boolean: conditional types distribute over unions when T is a bare type parameter
    Wrap both sides in brackets ([T] extends [string]) to stop distribution.
  24. 24
    What does infer do?
    Captures a type inside a conditional type
    ts
    type ElementOf<T> = T extends (infer U)[] ? U : never
  25. 25
    Partial<T> vs Required<T>
    Partial makes every property optional; Required makes every property required
  26. 26
    Pick<T, K> vs Omit<T, K>
    Pick keeps only the listed keys; Omit keeps everything except them
    ts
    type Preview = Pick<Post, 'id' | 'title'>
  27. 27
    What is Record<K, V>?
    An object type with keys K and values V
    ts
    const counts: Record<string, number> = {}
  28. 28
    Get a function’s return and parameter types
    ReturnType<typeof fn> and Parameters<typeof fn>
  29. 29
    What does Awaited<T> do?
    Unwraps promises recursively
    ts
    type N = Awaited<Promise<Promise<number>>> // number
  30. 30
    Exclude<T, U> vs Extract<T, U>
    Exclude removes union members assignable to U; Extract keeps only those
    ts
    type BC = Exclude<'a' | 'b' | 'c', 'a'> // 'b' | 'c'
  31. 31
    What does NonNullable<T> remove?
    null and undefined
    ts
    type S = NonNullable<string | null> // string
  32. 32
    Type an array that can’t be modified
    readonly string[] (or ReadonlyArray<string>); push and index assignment are errors
  33. 33
    What does as const do?
    Infers the narrowest literal types and makes everything readonly
    ts
    const dirs = ['up', 'down'] as const // readonly ['up', 'down']
  34. 34
    Turn an as const array into a union type
    ts
    const dirs = ['up', 'down'] as const
    type Dir = (typeof dirs)[number] // 'up' | 'down'
  35. 35
    What does satisfies do?
    Checks a value against a type without widening the value’s inferred type
    ts
    const routes = { home: '/', docs: '/docs' } satisfies Record<string, string>
    routes.docs // ok; routes.blog is an error
  36. 36
    as vs satisfies
    as overrides the checker and can hide mistakes; satisfies validates and keeps the precise type
  37. 37
    What does the ! in el!.focus() do?
    Asserts the value isn’t null or undefined. It’s erased at compile time; there’s no runtime check
  38. 38
    String enum vs union of string literals
    A union adds no runtime code and accepts plain strings; an enum generates a runtime object you must import
    Enums aren’t erasable syntax, so tools that only strip types (like Node’s built-in TypeScript support) can’t run them.
  39. 39
    Template literal type
    ts
    type Handler = `on${Capitalize<'click' | 'focus'>}` // 'onClick' | 'onFocus'
  40. 40
    Labeled tuple type
    ts
    type Point = [x: number, y: number]
  41. 41
    Type a function that concatenates two tuples
    ts
    function concat<A extends unknown[], B extends unknown[]>(a: [...A], b: [...B]): [...A, ...B] {
      return [...a, ...b]
    }
  42. 42
    name?: string vs name: string | undefined
    With ? the key may be missing; with | undefined the key must be present (its value may be undefined)
  43. 43
    What does strict: true enable?
    A family of checks, including strictNullChecks, noImplicitAny, strictFunctionTypes and useUnknownInCatchVariables
  44. 44
    What changes with strictNullChecks?
    null and undefined are no longer assignable to other types unless the type includes them
  45. 45
    What does noUncheckedIndexedAccess do?
    Index access on arrays and index signatures returns T | undefined, so you must handle the missing case
  46. 46
    Write function overloads
    ts
    function parse(x: string): number
    function parse(x: number): string
    function parse(x: string | number) {
      return typeof x === 'string' ? Number(x) : String(x)
    }
    Callers only see the overload signatures, not the implementation signature.
  47. 47
    What does import type do?
    Imports something only for type checking; it’s removed from the emitted JavaScript
    ts
    import type { User } from './types'
  48. 48
    What does verbatimModuleSyntax enforce?
    Imports without type are kept in the output as written, so type-only imports must be marked with type
  49. 49
    Index signature
    Allows any key of a given type
    ts
    type Scores = { [player: string]: number }
  50. 50
    Default for a type parameter
    ts
    type ApiResponse<T = unknown> = { data: T; status: number }

Frequently asked questions

Do I need to know JavaScript first?

Yes. TypeScript adds types on top of JavaScript, so this deck assumes you already write JavaScript.

Which TypeScript version does it cover?

TypeScript 5.x: satisfies, strict mode flags and modern module settings like verbatimModuleSyntax.

Is it useful for interviews?

Yes. Narrowing, generics, keyof and utility types are common interview topics for TypeScript roles.

Intermediate

JavaScript

Master the JavaScript every developer uses daily: scope, closures, equality, array methods, promises, async/await and the event loop.

50 cards
Intermediate

Advanced JS

Fifty advanced JavaScript cards: event-loop ordering puzzles, generators and async iteration, this binding, Proxy and Reflect, modules, AbortController and coercion edge cases.

50 cards
Beginner

Python

Learn idiomatic Python fast: comprehensions, f-strings, args and kwargs, generators, decorators, context managers and the standard library.

50 cards
Beginner

Git & terminal

The Git commands and shell skills developers use every day: branching, rebasing, undoing mistakes, pipes, redirects, permissions and processes.

50 cards
Beginner

Java

Core Java with short snippets: equals vs ==, records, sealed types, collections, generics, exceptions, streams, lambdas and JVM basics.

50 cards
Beginner

C#

C# and .NET fundamentals with short snippets: value vs reference types, properties, records, nullable reference types, LINQ, async/await and DI.

50 cards
Beginner

Kotlin

Kotlin fundamentals with short snippets: null safety, val vs var, data and sealed classes, extension functions, scope functions and coroutines.

50 cards
Beginner

Swift

Swift fundamentals with short snippets: optionals, structs vs classes, protocols, enums with associated values, closures, ARC, async/await and SwiftUI.

50 cards
Beginner

Flutter

Flutter and Dart basics: null safety, futures and streams, stateless vs stateful widgets, setState, hot reload, keys, layout and state management.

50 cards
Beginner

PHP

Modern PHP 8 with short snippets: strict types, arrays, match, nullsafe and named arguments, enums, readonly, Composer, PDO and password_hash.

50 cards
Beginner

Ruby

Ruby fundamentals with short snippets: blocks, procs and lambdas, symbols, Enumerable, mixins, truthiness, method_missing, gems and Bundler.

50 cards
Beginner

Go

Go (Golang) fundamentals with short, idiomatic snippets: slices vs arrays, maps, defer, error wrapping, interfaces, goroutines, channels, select and context.

50 cards
Intermediate

Rust

Learn the Rust that the compiler keeps asking about: ownership, borrowing, lifetimes, Option and Result, traits, closures, smart pointers and async.

50 cards
Intermediate

C++

Modern C++ in short snippets: references vs pointers, RAII, smart pointers, move semantics, STL containers and algorithms, const, templates and UB.

50 cards
Intermediate

Haskell

Haskell fundamentals with short code: types and type classes, pattern matching, laziness, Maybe and Either, folds, Functor, Applicative and Monad.

50 cards
Intermediate

Elixir

Elixir fundamentals with short snippets: immutability, pattern matching, the pipe operator, Enum vs Stream, processes, GenServer, supervisors and mix.

50 cards
Intermediate

x86-64 assembly

x86-64 assembly in Intel syntax: registers and sub-registers, flags, mov and lea, jumps, the stack frame, the System V calling convention and Linux syscalls.

50 cards
Beginner

Regex

Learn regular expressions for good: anchors, classes, greedy vs lazy quantifiers, groups, lookarounds, flags, replacements and the backtracking trap.

50 cards