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.
Practice now
Study without an account
type vs interfaceScheduled with the default Askesis timings. Progress is saved in this browser.
All 50 cards
- 1
typevsinterfaceBoth describe object shapes; interfaces can be reopened and merged, type aliases can also name unions, tuples, primitives and mapped types - 2What is declaration merging?Two
interfacedeclarations with the same name merge into one with all memberstsinterface User { id: string } interface User { name: string } const u: User = { id: '1', name: 'Ada' } - 3What can you do with a value of type
string | numberbefore narrowing?Only what both members support (e.g.toString()) - 4Narrow a union with
typeoftsfunction format(v: string | number) { if (typeof v === 'number') return v.toFixed(2) return v.trim() // v is string here } - 5Narrow with the
inoperatortsfunction move(a: Fish | Bird) { if ('swim' in a) a.swim() else a.fly() } - 6What is a discriminated union?A union whose members share a literal property (like
kind) that narrows the type when checkedtstype 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 } - 7How do you make a
switchover a union exhaustive?Assign the value toneverin the default branch; a new, unhandled member becomes a compile errortsdefault: { const unreachable: never = s throw new Error(`Unhandled: ${unreachable}`) } - 8
unknownvsanyanyswitches type checking off;unknownaccepts anything but must be narrowed before use - 9What is the
nevertype?The type with no values: functions that always throw, impossible branches, the empty union - 10Can a
() => voidcallback type accept a function that returns a value?Yes.voidthere means the return value is ignored, soarr.forEach(x => list.push(x))type-checks - 11Write a user-defined type guardts
function isString(x: unknown): x is string { return typeof x === 'string' } - 12Write an assertion functionts
function assert(cond: unknown, msg?: string): asserts cond { if (!cond) throw new Error(msg) }Declare it withfunctionor an explicitly typed const; TypeScript rejects calls through an unannotated arrow. - 13A generic function returning the first elementts
function first<T>(items: T[]): T | undefined { return items[0] } - 14Constrain a type parameterts
function longest<T extends { length: number }>(a: T, b: T): T { return a.length >= b.length ? a : b } - 15What does
keyofproduce?A union of an object type’s keyststype K = keyof { a: 1; b: 2 } // 'a' | 'b' - 16
typeofin a type positionThe type of a valuetsconst config = { port: 3000, host: "localhost" } type Config = typeof config // { port: number; host: string } - 17What is an indexed access type?Looking up a property’s type by key, like
Config["port"];T[number]gives an array’s element type - 18Type a safe property getterts
function get<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key] } - 19What is a mapped type?A type built by iterating over keysts
type Flags<T> = { [K in keyof T]: boolean } - 20Remove
readonlyand?in a mapped typePrefix the modifier with-tstype Concrete<T> = { -readonly [K in keyof T]-?: T[K] } - 21Rename keys in a mapped typeUse an
asclausetstype Getters<T> = { [K in keyof T as `get${Capitalize<string & K>}`]: () => T[K] } - 22Conditional type syntaxts
type IsString<T> = T extends string ? true : false - 23What is
IsString<string | number>ifIsString<T> = T extends string ? true : false?boolean: conditional types distribute over unions whenTis a bare type parameterWrap both sides in brackets ([T] extends [string]) to stop distribution. - 24What does
inferdo?Captures a type inside a conditional typetstype ElementOf<T> = T extends (infer U)[] ? U : never - 25
Partial<T>vsRequired<T>Partialmakes every property optional;Requiredmakes every property required - 26
Pick<T, K>vsOmit<T, K>Pickkeeps only the listed keys;Omitkeeps everything except themtstype Preview = Pick<Post, 'id' | 'title'> - 27What is
Record<K, V>?An object type with keysKand valuesVtsconst counts: Record<string, number> = {} - 28Get a function’s return and parameter types
ReturnType<typeof fn>andParameters<typeof fn> - 29What does
Awaited<T>do?Unwraps promises recursivelytstype N = Awaited<Promise<Promise<number>>> // number - 30
Exclude<T, U>vsExtract<T, U>Excluderemoves union members assignable toU;Extractkeeps only thosetstype BC = Exclude<'a' | 'b' | 'c', 'a'> // 'b' | 'c' - 31What does
NonNullable<T>remove?nullandundefinedtstype S = NonNullable<string | null> // string - 32Type an array that can’t be modified
readonly string[](orReadonlyArray<string>);pushand index assignment are errors - 33What does
as constdo?Infers the narrowest literal types and makes everythingreadonlytsconst dirs = ['up', 'down'] as const // readonly ['up', 'down'] - 34Turn an
as constarray into a union typetsconst dirs = ['up', 'down'] as const type Dir = (typeof dirs)[number] // 'up' | 'down' - 35What does
satisfiesdo?Checks a value against a type without widening the value’s inferred typetsconst routes = { home: '/', docs: '/docs' } satisfies Record<string, string> routes.docs // ok; routes.blog is an error - 36
asvssatisfiesasoverrides the checker and can hide mistakes;satisfiesvalidates and keeps the precise type - 37What does the
!inel!.focus()do?Asserts the value isn’tnullorundefined. It’s erased at compile time; there’s no runtime check - 38String enum vs union of string literalsA union adds no runtime code and accepts plain strings; an
enumgenerates a runtime object you must importEnums aren’t erasable syntax, so tools that only strip types (like Node’s built-in TypeScript support) can’t run them. - 39Template literal typets
type Handler = `on${Capitalize<'click' | 'focus'>}` // 'onClick' | 'onFocus' - 40Labeled tuple typets
type Point = [x: number, y: number] - 41Type a function that concatenates two tuplests
function concat<A extends unknown[], B extends unknown[]>(a: [...A], b: [...B]): [...A, ...B] { return [...a, ...b] } - 42
name?: stringvsname: string | undefinedWith?the key may be missing; with| undefinedthe key must be present (its value may beundefined) - 43What does
strict: trueenable?A family of checks, includingstrictNullChecks,noImplicitAny,strictFunctionTypesanduseUnknownInCatchVariables - 44What changes with
strictNullChecks?nullandundefinedare no longer assignable to other types unless the type includes them - 45What does
noUncheckedIndexedAccessdo?Index access on arrays and index signatures returnsT | undefined, so you must handle the missing case - 46Write function overloadsts
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. - 47What does
import typedo?Imports something only for type checking; it’s removed from the emitted JavaScripttsimport type { User } from './types' - 48What does
verbatimModuleSyntaxenforce?Imports withouttypeare kept in the output as written, so type-only imports must be marked withtype - 49Index signatureAllows any key of a given typets
type Scores = { [player: string]: number } - 50Default for a type parameterts
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.
More in Programming
JavaScript
Master the JavaScript every developer uses daily: scope, closures, equality, array methods, promises, async/await and the event loop.
50 cardsAdvanced 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 cardsPython
Learn idiomatic Python fast: comprehensions, f-strings, args and kwargs, generators, decorators, context managers and the standard library.
50 cardsGit & terminal
The Git commands and shell skills developers use every day: branching, rebasing, undoing mistakes, pipes, redirects, permissions and processes.
50 cardsJava
Core Java with short snippets: equals vs ==, records, sealed types, collections, generics, exceptions, streams, lambdas and JVM basics.
50 cardsC#
C# and .NET fundamentals with short snippets: value vs reference types, properties, records, nullable reference types, LINQ, async/await and DI.
50 cardsKotlin
Kotlin fundamentals with short snippets: null safety, val vs var, data and sealed classes, extension functions, scope functions and coroutines.
50 cardsSwift
Swift fundamentals with short snippets: optionals, structs vs classes, protocols, enums with associated values, closures, ARC, async/await and SwiftUI.
50 cardsFlutter
Flutter and Dart basics: null safety, futures and streams, stateless vs stateful widgets, setState, hot reload, keys, layout and state management.
50 cardsPHP
Modern PHP 8 with short snippets: strict types, arrays, match, nullsafe and named arguments, enums, readonly, Composer, PDO and password_hash.
50 cardsRuby
Ruby fundamentals with short snippets: blocks, procs and lambdas, symbols, Enumerable, mixins, truthiness, method_missing, gems and Bundler.
50 cardsGo
Go (Golang) fundamentals with short, idiomatic snippets: slices vs arrays, maps, defer, error wrapping, interfaces, goroutines, channels, select and context.
50 cardsRust
Learn the Rust that the compiler keeps asking about: ownership, borrowing, lifetimes, Option and Result, traits, closures, smart pointers and async.
50 cardsC++
Modern C++ in short snippets: references vs pointers, RAII, smart pointers, move semantics, STL containers and algorithms, const, templates and UB.
50 cardsHaskell
Haskell fundamentals with short code: types and type classes, pattern matching, laziness, Maybe and Either, folds, Functor, Applicative and Monad.
50 cardsElixir
Elixir fundamentals with short snippets: immutability, pattern matching, the pipe operator, Enum vs Stream, processes, GenServer, supervisors and mix.
50 cardsx86-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 cardsRegex
Learn regular expressions for good: anchors, classes, greedy vs lazy quantifiers, groups, lookarounds, flags, replacements and the backtracking trap.
50 cards