Polaris ML/AI Training

TypeScript for Foundry: From First Script to OSDK

beginner46h27 lessons

Learn TypeScript from the ground up — variables, types, functions, classes, generics, async/await — then put it to work in Palantir Foundry: typed OSDK queries and actions, Code Repository Functions you actually test and invoke, and how to debug all of it. Act 4 takes that code to production: types and Zod validation at the boundary, a production Foundry client with retries and error classes, safe idempotent writes, querying at scale, testing, shipping a Node service, and a capstone Next.js app on the OSDK. No TypeScript experience required. Some Palantir Foundry background is assumed — if Foundry itself is new to you, start with the Palantir Hands-On Bootcamp first. Bilingual (English + 中文).

TypeScriptFoundryOSDKPalantirJavaScriptAsync/AwaitGenericsCode RepositoriesFunctionsDebuggingZodTestingVitestProductionNext.jsBeginner

Premium content

Upgrade to premium to access all lessons, tutorials, and hands-on exercises.

Lesson Overview

1

Lesson 1: Why TypeScript & Your Dev Environment

Understand what TypeScript actually adds over JavaScript — static types checked at compile time instead of runtime — through a real type-coercion bug, then stand up a genuine local toolchain: npm init, TypeScript and tsx installed, a tsconfig.json you understand field by field, and VS Code catching type errors live.

2

Lesson 2: Variables, Primitive Types & Type Inference

Distinguish let/const, primitive types, any/unknown/never, and when to let inference work vs annotate explicitly — the foundation every later Act 1 lesson builds on.

3

Lesson 3: Arrays, Tuples & Object Types

Type collections and structured records — arrays, fixed-shape tuples, and object types with optional and readonly fields — by hand-typing a technician roster, a coordinate tuple, and a nested service-call record from scratch.

4

Lesson 4: Functions in TypeScript

Write scoreTechnician and routeWorkOrder from scratch with full parameter and return typing, mastering optional, default, and rest parameters along the way — then define a reusable function type alias so scoring strategies can be passed around as values.

5

Lesson 5: Union Types, Literal Types, Enums & Narrowing

Model a field that can only hold one of a few known values with union types, literal types, and enums, then safely narrow those values with typeof, in, and discriminated unions — the pattern you'll apply yourself to OSDK fields like RegionalSales.status, which the generated SDK types as a plain string.

6

Lesson 6: Interfaces vs. Type Aliases

Learn when to reach for interface versus type, how TypeScript's structural typing actually works, and how extends, readonly, and optional properties shape real object types — then hand-write a simplified version of the RegionalSales interface that OSDK's code generator will later produce for you automatically.

7

Lesson 7: Classes in TypeScript

Learn constructors, access modifiers, readonly, inheritance, and implementing an interface by building a TechnicianScorer class — a direct rehearsal for the RiskScoring class you'll write in the capstone.

8

Lesson 8: Generics — the Basics

Write generic functions and generic interfaces, constrain a type parameter with `extends` so it's safe to use inside the function body, and see exactly why the typed OSDK client you'll use later in this course has to be generic to work for any ontology object type.

9

Lesson 9: Async/Await & Promises

Type Promise<T> correctly, write async functions with honest return types, and handle a rejected promise with try/catch and instanceof narrowing — then run independent calls concurrently with Promise.all. Build a fetch-shaped fake API and break it on purpose, because this exact pattern is what every OSDK call in this course depends on.

10

Lesson 10: Modules, npm, tsconfig & Reading Compiler Errors

Learn how TypeScript files connect through import/export, how npm and package.json manage your project's dependencies, which tsconfig.json options actually matter for a Foundry-style project, and how to read the five compiler error codes every beginner hits — TS2322, TS2339, TS2345, TS7006, and TS2532/TS18048.

11

Lesson 11: OSDK Setup, Auth & Typed Queries

Generate an OSDK package with @osdk/foundry-sdk-generator, wire up a confidential-client auth.ts, and run fully typed where/select/orderBy/pageSize queries against RegionalSales, paging through the results both by hand and with asyncIter.

12

Lesson 12: Typed Actions & the OSDK Idiom

Apply the setRegionStatus Action through the typed OSDK client, deliberately trigger a runtime rejection using a status value outside the RegionStatus literal union from Act 1, and see exactly why applyAction() throws instead of returning a validation.result block the way the raw REST Actions API does.

13

Lesson 13: Code Repository Functions — Write & Type It Right

Reuse the RiskScoring Function from the Palantir capstone verbatim, then rewrite it with Act 1 class syntax and zero inferred `any`, and see exactly why a Function-decorated class differs from a Transform Code Repository.

14

Lesson 14: Unit-Testing and Invoking Functions for Real

Unit-test the actual decorated RiskScoring Function class (not a reimplementation), then publish it and invoke it externally via OSDK.

15

Lesson 15: Generating Your SDK Locally with @osdk/foundry-sdk-generator

Move Foundry SDK generation off Developer Console's Generate button and onto a scripted, CI-checkable @osdk/foundry-sdk-generator pipeline.

16

Lesson 16: Reading & Fixing TS Compiler Errors in a Foundry Project

Go deeper than Act 1's generic compiler-error lesson and learn to read the three error shapes that come specifically from a generated OSDK SDK and Foundry's ontology-api types — stale imports after an Ontology change, possibly-undefined optional properties under strict mode, and malformed applyAction calls — then trigger and fix all three yourself.

17

Lesson 17: Debugging OSDK & Foundry Runtime Errors

Recognize and resolve Foundry-specific runtime error shapes — auth and token failures, thrown Action rejections, and stale pagination tokens — using the Node inspector, the VS Code debugger, and the browser Network tab.

18

Lesson 18: Capstone Debugging Lab — Diagnose & Fix Broken OSDK Code

Apply everything from Acts 1–3 to one realistic scenario: diagnose and fix a roughly 40-line OSDK script seeded with five deliberate bugs — a missing await, a missing token scope, a REST-style validation check that OSDK doesn't support, an incomplete pagination loop, and a stale generated field name. You leave with a repeatable five-question framework for finding bugs like these on your own.

19

Lesson 19 (Bonus): Pilot — Generate an OSDK App, Then Read & Debug Its TypeScript

Palantir Pilot generates an OSDK app from one prompt — you review it like a code reviewer. Scope Pilot to a read-only ontology, read the generics, unions and optional chaining it wrote, turn its own caveat into a precise fix request, unpack the primary-key nullability trap, and verify the fix yourself. Captured live in a Foundry training sandbox.

20

Lesson 20: Types at the Boundary — Utility, Mapped & Template-Literal Types, satisfies

Open Act 4 with the type-level toolkit production Foundry code leans on: utility types, as const unions, satisfies, exhaustive Record registries, a little infer, template-literal types (the same trick behind the OSDK's "revenue:sum" keys), ?: never exclusive shapes, open unions for server vocabularies and branded primary keys, all combined into a status-policy.ts module that handles statuses it has never seen.

21

Lesson 21: Runtime Validation with Zod — Env, Wire Contracts & Unknown Errors

Replace Lesson 11's non-null assertions and Lesson 12's hand-written type predicate with Zod 4 schemas: a mode-aware env.ts that reports every problem without leaking secrets, z.infer contracts shared by server and client, strict request bodies, discriminated-union webhooks, and a never-throwing normaliser for unknown errors, all tied together in a tested handleSetStatus.

22

Lesson 22: A Production Foundry Client — Tokens, Retries, Timeouts & Error Classes

Read what @osdk/client and @osdk/oauth already do — cached single-flight tokens, built-in 429/503 retries even for writes, no timeouts — then build the rest: a client factory, per-attempt AbortSignal timeouts, a skewed single-flight token cache that re-authenticates once on 401, a tested withRetry with full jitter and Retry-After, errors classified as data, three-state lookups, and logs that never leak.

23

Lesson 23: Safe Actions — Validate, Apply, Recover the Key, Never Duplicate

Build a production write path for the createSalesRep Action: pre-flight checks that turn vague rejections into precise errors, $validateOnly dry runs, $returnEdits with primary-key recovery, a client-chosen requestId so retries never duplicate, rejected-vs-unknown outcomes as a discriminated union, batches that name each bad item, and a parking lot for writes that need replaying.

24

Lesson 24: Querying at Scale — Links, Aggregations, Object Sets & Interfaces

Make Ontology reads fast and honest at any size: replace N+1 link loops with pivotTo and chunked $in queries, count with aggregate instead of downloading rows, combine object sets, page safely with a PageLimitError ceiling, query across types with the Trackable interface, handle GeoJSON points and live subscriptions, then build and test region-dashboard.ts.

25

Lesson 25: Testing Foundry Code — Fakes, Mock Clients, Fake Timers & Live Gates

Build a six-rung testing ladder for Foundry code with Vitest 5 — pure functions, Pick<>-narrowed fakes, the experimental OSDK mock client, a stubbed fetch router, fake timers, and an in-memory fake ontology — then guard the suite with gated live tests and a scope inventory.

26

Lesson 26: Shipping a Node Service — tsconfig, Lint Boundaries, Bundling, Secrets & Logs

Turn a working OSDK script into a service you can deploy and trust: several tsconfigs so nothing goes stale, strict flags beyond strict, path aliases that survive the build, type-aware lint rules and an import boundary around the Foundry client, an esbuild bundle for Node 24, secrets loaded late and reported by name, redacted pino logs with honest levels, and a graceful SIGTERM shutdown — packaged as the region-health service in a slim container.

27

Lesson 27: Capstone — A Next.js App on the OSDK

Build TechFlow Region Desk, the Next.js app this course has promised from the start: a server-only confidential OSDK client, a live Server Component page with per-status aggregates, a Zod-validated route handler that turns action failures into 422/502/504 responses, a small optimistic Client Component form, route-handler tests with a fake Foundry, the per-user PKCE alternative, and a typed backend proxy for mobile clients.

TypeScript for Foundry: From First Script to OSDK | ML/AI Bootcamp | Polaris ML/AI Training