JavaScript and TypeScript for Kotlin developers
Why it matters
- React Native's JavaScript/TypeScript layer has two empty values (
nullandundefined) where Kotlin has one. Missing the distinction causesTypeError: Cannot read properties of undefinedat 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/awaitdiffers from Kotlin coroutines: no structured concurrency, noCoroutineScope, no built-in cancellation. Knowing the gap shows you understand the runtime. - TypeScript's
anytype 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'sstring | null | undefinedis 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/awaitis like a coroutine with noCoroutineScopeand noJob: once aPromisestarts, nothing outside can cancel it unless the code cooperates (for example with anAbortSignal).constin TypeScript is like Kotlin'sval: 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.
| Kotlin | TypeScript | Note |
|---|---|---|
String? | string | null | undefined | One empty value vs two |
sealed class | type A = { tag: "x" } | { tag: "y" } | Discriminated union, checked by tag |
suspend fun / Deferred<T> | async function / Promise<T> | No scope, no automatic cancellation |
val / var | const / let | Neither makes the object immutable |
when (x) { is T -> } | switch on a tag, typeof, instanceof | TS narrows the type after the check |
a == b / a === b | no equals / a === b | JS === 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
nullandundefinedare distinct types in TypeScript withstrictNullChecks. A missing property, an unassigned variable and a function with noreturnall giveundefined. Kotlin has onlynull.strictNullChecksis enabled bystrict: trueintsconfig.json. Without it,nullandundefinedare assignable to every type, which is like turning off Kotlin's null safety.value == nullis true for bothnullandundefined;value === nullis true only fornull.??and?.handle both.- JavaScript
===compares primitives by value and objects by reference, like Kotlin's===. There is noequals(), so two objects with the same fields are never===. Avoid==except for the== nullcheck, because it coerces types. - TypeScript is structurally typed: any object with the right shape satisfies an interface. Kotlin is nominally typed.
constprevents reassignment of the binding, not mutation of the object.const arr: number[] = []; arr.push(1)is valid. Kotlin'svalbehaves the same way.- An
asyncfunction returns aPromise, which starts immediately, like Kotlin'sasync {}returning aDeferred. There is noCoroutineScope,JoborwithTimeout; cancelfetchwith anAbortController. - A discriminated union (
type Action = { type: "A"; x: number } | { type: "B"; y: string }) is TypeScript's equivalent of a Kotlinsealed class. Aswitchontypenarrows the type in each branch, and assigning the value toneverindefaultmakes 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 aTypeError. anydisables type checking for that value.unknownis safer: you must narrow it before use, like Kotlin'sAny?with anischeck.- Closures capture variables, not values. A
forloop withvarshares one variable across all iterations;letcreates a new binding per iteration, matching Kotlin's loop variable. - Optional properties (
email?: string) are typed asstring | undefined, notstring | null. JSON has noundefined: a missing key reads asundefined, while an explicitnullin the JSON staysnull. - An unhandled
Promiserejection 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?: stringproducesstring | undefined.user == nulland??handle both empty values, which is what a Kotlin developer expects from?.and?:.- The
switchonaction.typenarrowsactionto one member in eachcase, like Kotlin'swhenon a sealed class. Theneverassignment indefaultis how TypeScript gets an exhaustivewhen. fetchUsertakes an optionalAbortSignal. Passingcontroller.signaland callingcontroller.abort()is the manual version of cancelling a coroutineJob.
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
- A profile screen crashed for some users after the API started omitting
avatarUrlfor accounts without a photo. - The interface declared
avatarUrl: string, and the response was cast withas Profile, so the compiler trusted it. The component calledprofile.avatarUrl.replace("http:", "https:"). - At runtime
avatarUrlwasundefined, so the call threw aTypeErrorwhile rendering. Developers saw a red error screen; release users saw the app close, because the uncaught JS error was fatal. strictNullCheckswas on, but it could not help: the type said the field always existed.
- The team changed the type to
avatarUrl?: stringand rendered a fallback withprofile.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-assertionsrule to stop newascasts on API data.
- A screen fetched the selected user in a
useEffectthat 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 team created an
AbortControllerin the effect, passed itssignaltofetch, and calledcontroller.abort()in the effect's cleanup, so changing the ID cancels the old request. This is the manual version ofcollectLatestcancelling the previous coroutine. - Where a request could not be aborted, the cleanup set an
ignoreflag 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, soif (user.email === null)misses the common case. Useuser.email == nullor??. Avoidif (!user.email)when an empty string or0is a valid value, because it treats them as missing too. - Using any to silence a type error.
anydisables type checking for that value and everything derived from it, like an unchecked cast in Kotlin. Preferunknownand narrow it. Oneanyin a shared type spreads to every consumer. - Forgetting to await a Promise. Calling
fetchUser(id)withoutawaitgives you aPromise, not aUser. 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 startingasync {}and never callingawait(). typescript-eslint'sno-floating-promisesrule catches it. - Using var in a loop with a closure.
varis function-scoped, so every iteration shares one variable and every closure sees the final value. Useletorconst. - Treating const as immutable.
constprevents reassignment of the binding, not mutation of the object, exactly like Kotlin'sval. Usereadonlytypes orObject.freezewhen you need immutability. - Using the ! non-null assertion instead of a guard.
user!.nameonly silences the compiler. Unlike Kotlin's!!, it does not throw at that point; ifuserisnull, theTypeErrorhappens 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)
-
Create
actions.tsin a React Native project, or in a plain TypeScript project withstrict: trueintsconfig.json. -
Define a discriminated union:
type NavAction = | { type: "PUSH"; route: string; params?: Record<string, string> } | { type: "POP"; count?: number } | { type: "RESET" }; -
Write
describe(action: NavAction): stringthat returns a readable string for each variant, using aswitchonaction.type. ForPOP, useaction.count ?? 1. -
Add a
defaultcase containingconst unhandled: never = action; return unhandled;. Runnpx tsc --noEmitand confirm it compiles. -
Add a fourth variant
{ type: "REPLACE"; route: string }to the union without handling it. Runtscagain and confirm theneverline now fails with an error saying theREPLACEtype is not assignable tonever. HandleREPLACEto fix it. -
Write
describeOrNone(action: NavAction | null | undefined): stringthat returns"none"for both empty values with a singleaction == nullcheck, then callsdescribe(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".