Compares JavaScript and TypeScript with C#: dynamic vs static typing, structural typing and type erasure, null vs undefined, equality, promises vs Task, ES modules and npm, and common traps for C# developers.
JavaScript is dynamically typed and runs on a single-threaded event loop, unlike C#'s thread pool. TypeScript adds a static, structural type system on top, checked by tsc, then erased: at run time it's plain JavaScript, so a type annotation on a fetch result is a promise to the compiler, not a check, and API responses must be generated from the contract or validated (e.g. with zod). Compared with C#: types match by shape, not by name; there are two empties, null and undefined; numbers are all 64-bit floats; and you compare with ===. async/await looks identical to C#, but a Promise always resumes on the main thread, there is no ConfigureAwait and no blocking .Result. Code is organised as ES modules with import/export, packages come from npm. The trade-off: TypeScript gives C#-like tooling, but the safety stops at the network boundary.
"I think of TypeScript as JavaScript with a compile-time type checker. The compiler checks my code, then strips the types and emits JavaScript, so nothing about types exists at run time. That's the biggest mental shift from C#: if I write
const order = await res.json() as Order, I've told the compiler to trust me, and if the API actually returns{ orderId }instead of{ id }, nothing fails until I readundefinedsomewhere. So at the boundary I either generate types from the OpenAPI document or validate with a schema library like zod.The type system is also structural rather than nominal. In C#, an
OrderDtoand aCustomerDtowith the same properties are different types; in TypeScript, anything with the right shape fits. Unions and literal types, liketype Status = 'Draft' | 'Paid', are more expressive than C# enums, and discriminated unions withswitchgive you exhaustiveness checks.async/awaitreads exactly like C#, and a promise starts running as soon as it's created, like a hotTask. But JavaScript has one main thread, so every continuation comes back to it: there's no thread pool, noConfigureAwait, no deadlock from.Resultbecause there is no.Resultat all.The mistake I see C# developers make is assuming the runtime protects them: using
==and getting coercion, forgetting that0.1 + 0.2isn't0.3and there's nodecimalfor money, treatingundefinedandnullas the same, or losingthiswhen passing a method as a callback. Turning onstrictintsconfig.jsoncatches most of it. TypeScript gets you about 80% of C#'s safety inside the app; the other 20% you have to buy at the edges."
| Concept | C# | TypeScript / JavaScript |
|---|---|---|
| Typing | Static, nominal, enforced at run time | Static (TS), structural, erased at run time |
| Empty values | null (+ nullable reference types) |
null and undefined (strictNullChecks) |
| Numbers | int, long, decimal, double |
number (IEEE 754 double), bigint |
| Equality | == with operator overloading |
=== strict; == coerces types |
| Async | Task, thread pool, SynchronizationContext |
Promise, single main thread, microtasks |
| Modules | Assemblies, namespaces, NuGet | ES modules (import/export), npm |
| Generics | Reified at run time | Erased at run time |
| Enums | Value types | Prefer string-literal unions |
| Feature | What it does |
|---|---|
| Union and literal types | 'Draft' \| 'Paid' restricts values |
| Discriminated unions | Exhaustive switch on a kind field |
Partial<T>, Pick<T,K>, Omit<T,K> |
Derive types without copying |
unknown vs any |
unknown forces a check before use |
satisfies |
Checks a value against a type without widening |
A team typed API responses by hand with as Order. After the backend renamed totalAmount to total, the UI showed $NaN for two days before anyone noticed. Generating TypeScript types from the ASP.NET Core OpenAPI document in CI turned the next rename into a compile error that blocked the merge.
Checks whether a C# developer can work productively and safely in a TypeScript codebase without carrying wrong assumptions across.
Green flags
strict, ===, null vs undefinedRed flags
any everywhere as the fix .ts / .tsx source
|
tsc (type check only) esbuild / Vite (strip types, bundle)
| |
errors or OK plain .js modules -> browser
Most modern toolchains (Vite uses esbuild) strip types without checking them, so you run tsc --noEmit separately in CI. Type checking and emitting are separate steps.
type Point = { x: number; y: number };
const p = { x: 1, y: 2, label: 'a' };
const q: Point = p; // OK: p has at least x and y
This is great for JSON, which has no class names, but it means two unrelated types with the same shape are interchangeable. Use branded types (string & { __brand: 'OrderId' }) if you need C#-style distinctness.
C# Task |
JS Promise |
|
|---|---|---|
| Starts | Hot (usually) | Hot (executor runs immediately) |
| Continuation runs on | Thread pool or captured context | Main thread, as a microtask |
| Blocking wait | .Result / .Wait() (dangerous) |
Not possible |
| Cancellation | CancellationToken |
AbortSignal (by convention) |
| Combinators | Task.WhenAll, WhenAny |
Promise.all, allSettled, race, any |
| Unhandled failure | TaskScheduler.UnobservedTaskException |
unhandledrejection event |
Each file is a module with its own scope. import { getOrders } from './api/orders' is resolved at build time by the bundler. package.json is the .csproj equivalent; package-lock.json pins exact versions like a lock file. The npm ecosystem has many tiny packages, so supply-chain risk (typosquatting, compromised maintainers) is real: use npm ci, a lock file and npm audit.
this and closuresIn JavaScript, this is decided by how a function is called, not where it's defined. Passing obj.method as a callback loses this. Arrow functions capture this from the surrounding scope, so they're the default in modern code.
npm create vite@latest demo -- --template react-ts, open tsconfig.json and confirm strict: true.const o = JSON.parse('{"id":"1"}') as { id: number } and log typeof o.id to see erasure.0 == '', 0 === '', null == undefined and 0.1 + 0.2.switch and add a never default to get an exhaustiveness error when you add a case.tsc --noEmit and vite build and note that only the first fails on a type error.The same idea in C# and TypeScript: a DTO, a status union and an async call.
// C#: nominal types, enums, Task
namespace Shop.Api;
public enum OrderStatus { Draft, Paid, Shipped }
public sealed record OrderDto(int Id, decimal Total, OrderStatus Status);
public sealed class OrdersClient(HttpClient http)
{
public async Task<OrderDto?> GetAsync(int id, CancellationToken ct) =>
await http.GetFromJsonAsync<OrderDto>($"/api/orders/{id}", ct); // deserialises and checks types
}
// TypeScript: structural types, string-literal union, Promise
export type OrderStatus = 'Draft' | 'Paid' | 'Shipped';
export type OrderDto = {
id: number;
total: number; // JSON numbers are doubles: format money carefully, or send it as a string
status: OrderStatus;
};
export async function getOrder(id: number, signal?: AbortSignal): Promise<OrderDto> {
const res = await fetch(`/api/orders/${id}`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()) as OrderDto; // a cast, NOT a check: types are erased at run time
}
export function label(status: OrderStatus): string {
switch (status) {
case 'Draft': return 'Not paid yet';
case 'Paid': return 'Paid';
case 'Shipped': return 'On its way';
default: {
const unreachable: never = status; // compile error if a new status is added
return unreachable;
}
}
}
as SomeType on a JSON response as validation. Why it is wrong: Types are erased; nothing is checked at run time. Instead: Generate types from OpenAPI and validate untrusted data with a schema (zod, valibot).==. Why it is wrong: It coerces types (0 == '' is true). Instead: Always ===, enforced by ESLint eqeqeq.number. Why it is wrong: Floating point gives 0.30000000000000004. Instead: Calculate on the server with decimal, or use integer cents.strict to make errors go away. Why it is wrong: You lose null checks and implicit-any detection. Instead: Keep strict: true; fix or narrow types.any. Why it is wrong: It switches off checking and spreads silently. Instead: Use unknown and narrow.this.method as a callback. Why it is wrong: this becomes undefined when called. Instead: Use arrow functions or .bind.await or .catch. Why it is wrong: Failures become unhandled rejections and vanish. Instead: Await them or handle the rejection; enable @typescript-eslint/no-floating-promises.For a .NET team the biggest win is sharing the contract, not the code: ASP.NET Core in .NET 10 produces an OpenAPI document with Microsoft.AspNetCore.OpenApi, and tools such as openapi-typescript or Kiota generate the frontend types, so a backend rename breaks the frontend build instead of production. Inside the app, strict TypeScript plus ESLint gives most of the safety C# developers expect.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Plain JavaScript | Tiny scripts, prototypes | No compile-time safety | Anything a team maintains |
TypeScript strict |
All app code | Build step, learning curve | Never really skip it for apps |
| TS + runtime validation (zod) | Untrusted or third-party data | Extra code and bundle bytes | Data you generate and control end to end |
Measure the value by counting production UI errors caused by contract drift (via Application Insights browser exceptions) before and after generating types.
On .NET 10, expose the OpenAPI document from ASP.NET Core with the built-in AddOpenApi / MapOpenApi (Microsoft.AspNetCore.OpenApi, available since .NET 9), then generate TypeScript in the build with openapi-typescript, Kiota or NSwag. Regenerate in CI and fail the build if the output changes unexpectedly, and run a breaking-change check (e.g. oasdiff) on the spec. Version the API (URL or header) and keep old contracts until clients move, so generated types for v1 and v2 can coexist. This turns a renamed field into a compile error instead of a production bug.
Cancellation in .NET is cooperative. A CancellationTokenSource owns the decision to cancel; it hands out CancellationTokens that code checks with IsCancellationRequested or ThrowIfCancellationRequested(), or passes to APIs that support it. When cancelled, the convention is to throw OperationCanceledException, which makes the task Canceled. Good APIs accept a CancellationToken as the last parameter (defaulting to default), pass it to every async call they make, and never swallow cancellation. In ASP.NET Core, a CancellationToken parameter is bound to HttpContext.RequestAborted, so client disconnects stop the work.
Last updated 23 Nov 2026.