JavaScript and TypeScript for Kotlin developers

Learn TypeScript for Kotlin developers moving to React Native: null vs undefined, async/await vs coroutines, closures, and unions vs sealed classes. About 25 minutes.

Why it matters

  • React Native's JavaScript/TypeScript layer has two empty values (null and undefined) where Kotlin has one. Missing the distinction causes TypeError: Cannot read properties of undefined at runtime, which shows a red error screen in development and, by default, is a fatal JS error in a release build.
  • Interviewers for cross-platform roles ask how async/await differs from Kotlin coroutines: no structured concurrency, no CoroutineScope, no built-in cancellation. Knowing the gap shows you understand the runtime.
  • TypeScript's any type works like an unchecked cast in Kotlin. It silently turns off type checking for everything it touches, and it spreads through a codebase faster than !! does in Kotlin.
  • Discriminated unions (TypeScript) and sealed classes (Kotlin) solve the same problem. Mapping them lets you read a React Native reducer or navigation state file without translating every line.

The simple explanation

  • Kotlin's String? is a box that holds a string or nothing. TypeScript's string | null | undefined is a box that holds a string, was explicitly emptied (null), or was never filled (undefined).
  • A Kotlin sealed class is checked by its runtime type (is LoggedIn). TypeScript types are erased when the code runs, so a discriminated union is checked by reading a tag property (action.type === "LOGIN") instead.
  • async/await is like a coroutine with no CoroutineScope and no Job: once a Promise starts, nothing outside can cancel it unless the code cooperates (for example with an AbortSignal).
  • const in TypeScript is like Kotlin's val: the binding cannot be reassigned, but the object it points to can still be mutated.

How does TypeScript compare to Kotlin for a Kotlin developer learning React Native? TypeScript is JavaScript with a compile-time type system. It has null safety, generics, type inference and something close to sealed classes, so most Kotlin habits carry over. The traps are in the differences: two empty values, structural instead of nominal typing, types that disappear at runtime, and Promises without structured concurrency.

Null and undefined. Kotlin has one empty value: null. JavaScript has two. null usually means "deliberately empty". undefined is what you get from a variable that was never assigned, a missing object property or a function that returns nothing. With strictNullChecks (turned on by strict: true in tsconfig.json), the compiler makes you handle both. A Kotlin developer who checks only === null misses the undefined case. value == null (loose equality) and ?? treat both as empty.

Typing. Kotlin is nominal: a User is only a User if it was declared as one. TypeScript is structural: any object with the right properties fits the type. And because types are erased, res.json() as User checks nothing at runtime.

Async. Kotlin's suspend fun maps to an async function that returns a Promise<T>. A Promise is closer to Kotlin's Deferred<T> than to a suspend call: it starts running as soon as it is created, and you await it for the result. A rejected Promise that nobody catches becomes an unhandled rejection; there is no parent scope to propagate the failure to.

KotlinTypeScriptNote
String?string | null | undefinedOne empty value vs two
sealed classtype A = { tag: "x" } | { tag: "y" }Discriminated union, checked by tag
suspend fun / Deferred<T>async function / Promise<T>No scope, no automatic cancellation
val / varconst / letNeither makes the object immutable
when (x) { is T -> }switch on a tag, typeof, instanceofTS narrows the type after the check
a == b / a === bno equals / a === bJS === compares objects by reference
?. and ?:?. and ???? treats null and undefined as empty

The biggest gap: Kotlin's null safety cannot be switched off. TypeScript's can be bypassed with any, as casts and the ! non-null assertion, and none of these add a runtime check. In React Native the resulting error is a JS exception, not an Android ANR: the JS code runs on its own thread, separate from the Android main thread.

Notes

  • null and undefined are distinct types in TypeScript with strictNullChecks. A missing property, an unassigned variable and a function with no return all give undefined. Kotlin has only null.
  • strictNullChecks is enabled by strict: true in tsconfig.json. Without it, null and undefined are assignable to every type, which is like turning off Kotlin's null safety.
  • value == null is true for both null and undefined; value === null is true only for null. ?? and ?. handle both.
  • JavaScript === compares primitives by value and objects by reference, like Kotlin's ===. There is no equals(), so two objects with the same fields are never ===. Avoid == except for the == null check, because it coerces types.
  • TypeScript is structurally typed: any object with the right shape satisfies an interface. Kotlin is nominally typed.
  • const prevents reassignment of the binding, not mutation of the object. const arr: number[] = []; arr.push(1) is valid. Kotlin's val behaves the same way.
  • An async function returns a Promise, which starts immediately, like Kotlin's async {} returning a Deferred. There is no CoroutineScope, Job or withTimeout; cancel fetch with an AbortController.
  • A discriminated union (type Action = { type: "A"; x: number } | { type: "B"; y: string }) is TypeScript's equivalent of a Kotlin sealed class. A switch on type narrows the type in each branch, and assigning the value to never in default makes the compiler check exhaustiveness.
  • The ! non-null assertion (user!.name) tells the compiler "this is not null". Unlike Kotlin's !!, it is erased and does no runtime check, so the failure shows up later as a TypeError.
  • any disables type checking for that value. unknown is safer: you must narrow it before use, like Kotlin's Any? with an is check.
  • Closures capture variables, not values. A for loop with var shares one variable across all iterations; let creates a new binding per iteration, matching Kotlin's loop variable.
  • Optional properties (email?: string) are typed as string | undefined, not string | null. JSON has no undefined: a missing key reads as undefined, while an explicit null in the JSON stays null.
  • An unhandled Promise rejection in React Native shows a warning in development and does not crash the app, but the work silently fails and the screen can stay in a loading or broken state.

Code example

This TypeScript file shows the patterns that trip up Kotlin developers most: null/undefined handling with narrowing, async/await, closures in loops, and a discriminated union that mirrors a Kotlin sealed class.

// Kotlin: data class User(val id: Int, val name: String, val email: String? = null)
interface User {
  id: number;
  name: string;
  email?: string; // optional: string | undefined
}
 
// Kotlin: suspend fun fetchUser(id: Int): User?
// TS: an async function returns a Promise; there is no scope or Job
async function fetchUser(id: number, signal?: AbortSignal): Promise<User | null> {
  const res = await fetch(`https://api.example.com/users/${id}`, { signal });
  if (!res.ok) return null;
  // `as` is not checked at runtime; validate API data at the boundary in real code
  return (await res.json()) as User;
}
 
// Kotlin: user?.email ?: "No email"
function displayEmail(user: User | null | undefined): string {
  if (user == null) return "Unknown user"; // == null covers null and undefined
  // narrowed: user is User here
  return user.email ?? "No email";
}
 
// Closures: `let` gives each iteration its own binding (like Kotlin's loop variable)
const getters: Array<() => number> = [];
for (let i = 0; i < 3; i++) {
  getters.push(() => i);
}
console.log(getters.map((g) => g())); // [0, 1, 2]; with `var i` it would be [3, 3, 3]
 
// Discriminated union: Kotlin's sealed class equivalent
type Action =
  | { type: "FETCH"; id: number }
  | { type: "SET"; user: User }
  | { type: "CLEAR" };
 
function handleAction(action: Action): string {
  switch (action.type) {
    case "FETCH":
      return `fetching ${action.id}`;
    case "SET":
      return `set ${action.user.name}`;
    case "CLEAR":
      return "cleared";
    default: {
      // compile error here if a new Action member is not handled above
      const unhandled: never = action;
      return unhandled;
    }
  }
}
  • email?: string produces string | undefined. user == null and ?? handle both empty values, which is what a Kotlin developer expects from ?. and ?:.
  • The switch on action.type narrows action to one member in each case, like Kotlin's when on a sealed class. The never assignment in default is how TypeScript gets an exhaustive when.
  • fetchUser takes an optional AbortSignal. Passing controller.signal and calling controller.abort() is the manual version of cancelling a coroutine Job.

Run the idea in plain Kotlin

sealed interface Action {
  data class Fetch(val id: Int) : Action
  data class SetUser(val name: String) : Action
  data object Clear : Action
}

// Exhaustive when: TypeScript needs the never trick to get this check
fun handle(action: Action): String = when (action) {
  is Action.Fetch -> "fetching " + action.id
  is Action.SetUser -> "set " + action.name
  Action.Clear -> "cleared"
}

data class User(val name: String, val email: String? = null)

// TS: user?.email ?? "No email" (with null and undefined both treated as empty)
fun displayEmail(user: User?): String = user?.email ?: "No email"

fun main() {
  listOf(Action.Fetch(42), Action.SetUser("Ada"), Action.Clear).forEach { println(handle(it)) }

  println(displayEmail(User("Ada", "ada@example.com")))
  println(displayEmail(User("Bob")))
  println(displayEmail(null))

  // Each loop iteration has its own i, like let in TypeScript
  val getters = mutableListOf<() -> Int>()
  for (i in 0..2) getters.add { i }
  println("Kotlin loop closures: " + getters.map { it() })

  // One shared variable captured by every lambda, like var in a JS loop
  var shared = 0
  val sharedGetters = mutableListOf<() -> Int>()
  while (shared < 3) {
      sharedGetters.add { shared }
      shared++
  }
  println("One shared variable: " + sharedGetters.map { it() })

  // Kotlin == calls equals(); === compares references, like JS ===
  val a = User("Ada")
  val b = User("Ada")
  println("a == b: " + (a == b) + ", a === b: " + (a === b))
}

Expected output:

fetching 42
set Ada
cleared
ada@example.com
No email
No email
Kotlin loop closures: [0, 1, 2]
One shared variable: [3, 3, 3]
a == b: true, a === b: false

In production

Crash after an API response omits a field
  • A profile screen crashed for some users after the API started omitting avatarUrl for accounts without a photo.
  • The interface declared avatarUrl: string, and the response was cast with as Profile, so the compiler trusted it. The component called profile.avatarUrl.replace("http:", "https:").
  • At runtime avatarUrl was undefined, so the call threw a TypeError while rendering. Developers saw a red error screen; release users saw the app close, because the uncaught JS error was fatal.
  • strictNullChecks was on, but it could not help: the type said the field always existed.
The fix
  • The team changed the type to avatarUrl?: string and rendered a fallback with profile.avatarUrl ?? DEFAULT_AVATAR, so the compiler now forces the check.
  • They added runtime validation with a schema library at the API boundary, so a response that does not match the type is rejected in one place instead of crashing deep in the UI.
  • They added an error boundary around the screen so an unexpected render error shows a fallback instead of taking down the whole app.
  • They turned on the typescript-eslint consistent-type-assertions rule to stop new as casts on API data.
Race condition from overlapping fetches in an effect
  • A screen fetched the selected user in a useEffect that re-ran whenever the user ID changed.
  • Users who switched quickly between two profiles sometimes saw the wrong person: the first request resolved after the second and overwrote its result.
  • The bug was intermittent and hard to reproduce in development because network timing varied.
The fix
  • The team created an AbortController in the effect, passed its signal to fetch, and called controller.abort() in the effect's cleanup, so changing the ID cancels the old request. This is the manual version of collectLatest cancelling the previous coroutine.
  • Where a request could not be aborted, the cleanup set an ignore flag so a late response is dropped instead of written to state.
  • They added a test that resolves two overlapping requests out of order and asserts that only the latest result reaches state.

Common mistakes

  • Checking only for null. Optional properties produce undefined, so if (user.email === null) misses the common case. Use user.email == null or ??. Avoid if (!user.email) when an empty string or 0 is a valid value, because it treats them as missing too.
  • Using any to silence a type error. any disables type checking for that value and everything derived from it, like an unchecked cast in Kotlin. Prefer unknown and narrow it. One any in a shared type spreads to every consumer.
  • Forgetting to await a Promise. Calling fetchUser(id) without await gives you a Promise, not a User. The request still runs, but nothing waits for it and a failure becomes an unhandled rejection. In Kotlin a suspend call always waits, so there is no direct equivalent; the closest is starting async {} and never calling await(). typescript-eslint's no-floating-promises rule catches it.
  • Using var in a loop with a closure. var is function-scoped, so every iteration shares one variable and every closure sees the final value. Use let or const.
  • Treating const as immutable. const prevents reassignment of the binding, not mutation of the object, exactly like Kotlin's val. Use readonly types or Object.freeze when you need immutability.
  • Using the ! non-null assertion instead of a guard. user!.name only silences the compiler. Unlike Kotlin's !!, it does not throw at that point; if user is null, the TypeError happens on the property access, often far from the real cause.

Interview questions

Answer out loud first. Then reveal the answer and compare it at each depth.

“How does TypeScript handle null safety compared to Kotlin?”

“What is the difference between async/await in JavaScript and coroutines in Kotlin?”

“Explain the closure capture bug in JavaScript loops and why Kotlin developers rarely hit it.”

“How do discriminated unions in TypeScript compare to sealed classes in Kotlin?”

Quiz

In TypeScript, what value do you get when you read an optional property email?: string that is missing from the object?

What does const prevent in TypeScript?

An interface declares avatarUrl: string, the response is cast with as, and the API omits the field. A component calls profile.avatarUrl.replace("http:", "https:"). What happens?

Which TypeScript construct is the closest equivalent to a Kotlin sealed class?

0 of 4 answered

Mini task

Exercise: Type-narrow a discriminated union in TypeScript (15 min)

  1. Create actions.ts in a React Native project, or in a plain TypeScript project with strict: true in tsconfig.json.

  2. Define a discriminated union:

    type NavAction =
      | { type: "PUSH"; route: string; params?: Record<string, string> }
      | { type: "POP"; count?: number }
      | { type: "RESET" };
  3. Write describe(action: NavAction): string that returns a readable string for each variant, using a switch on action.type. For POP, use action.count ?? 1.

  4. Add a default case containing const unhandled: never = action; return unhandled;. Run npx tsc --noEmit and confirm it compiles.

  5. Add a fourth variant { type: "REPLACE"; route: string } to the union without handling it. Run tsc again and confirm the never line now fails with an error saying the REPLACE type is not assignable to never. Handle REPLACE to fix it.

  6. Write describeOrNone(action: NavAction | null | undefined): string that returns "none" for both empty values with a single action == null check, then calls describe(action).

Done when: npx tsc --noEmit reports zero errors, removing any case produces a compile error on the never line, and describeOrNone(null) and describeOrNone(undefined) both return "none".

Next: Components, props and hooks