📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

You're a C# developer joining a team with a TypeScript frontend. How do JavaScript and TypeScript compare with C#? Explain TypeScript's structural type system and type erasure, how async/await and promises differ from Task, how ES modules work, and the traps a C# developer usually falls into.

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.

Junior Theory Beginner async-await csharp es-modules frontend javascript typescript

🎯 Key points

  • TypeScript is JavaScript plus compile-time types; types are erased at run time
  • Structural typing: shape matters, not the declared name (unlike C# nominal typing), which suits JSON
  • No runtime type checks: generate types from OpenAPI or validate API responses (e.g. zod)
  • JS runs on one main thread with an event loop; no thread pool, no locks, no blocking waits
  • Promises start eagerly like Task; await always resumes on the main thread (no ConfigureAwait)
  • null and undefined are distinct; enable strict and strictNullChecks
  • Use === not ==; numbers are 64-bit floats (no decimal, no long)
  • ES modules: import/export per file, bundled by Vite/esbuild, packages from npm

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 read undefined somewhere. 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 OrderDto and a CustomerDto with the same properties are different types; in TypeScript, anything with the right shape fits. Unions and literal types, like type Status = 'Draft' | 'Paid', are more expressive than C# enums, and discriminated unions with switch give you exhaustiveness checks. async/await reads exactly like C#, and a promise starts running as soon as it's created, like a hot Task. But JavaScript has one main thread, so every continuation comes back to it: there's no thread pool, no ConfigureAwait, no deadlock from .Result because there is no .Result at all.

The mistake I see C# developers make is assuming the runtime protects them: using == and getting coercion, forgetting that 0.1 + 0.2 isn't 0.3 and there's no decimal for money, treating undefined and null as the same, or losing this when passing a method as a callback. Turning on strict in tsconfig.json catches 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."


C# vs TypeScript, side by side

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

Useful TypeScript features a C# dev will like

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

Production example

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.

🔍 What the interviewer is checking

Checks whether a C# developer can work productively and safely in a TypeScript codebase without carrying wrong assumptions across.

Green flags

  • Says types are erased and API data must be validated or generated
  • Explains structural vs nominal typing
  • Knows promise continuations run on the single main thread
  • Mentions strict, ===, null vs undefined

Red flags

  • Thinks TypeScript checks types at run time
  • Uses any everywhere as the fix
  • Believes JavaScript has threads like .NET

📚 Learn in depth

1. What TypeScript really is

  .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.

2. Structural typing

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.

3. Promises vs Task

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

4. Modules and packages

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.

5. this and closures

In 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.

Try it yourself

  1. Create a project with npm create vite@latest demo -- --template react-ts, open tsconfig.json and confirm strict: true.
  2. Write const o = JSON.parse('{"id":"1"}') as { id: number } and log typeof o.id to see erasure.
  3. In the console compare 0 == '', 0 === '', null == undefined and 0.1 + 0.2.
  4. Write a discriminated union with a switch and add a never default to get an exhaustiveness error when you add a case.
  5. Run tsc --noEmit and vite build and note that only the first fails on a type error.

💻 Code

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;
    }
  }
}

⚠ Common mistakes

  • Mistake: Treating 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).
  • Mistake: Using ==. Why it is wrong: It coerces types (0 == '' is true). Instead: Always ===, enforced by ESLint eqeqeq.
  • Mistake: Doing money arithmetic in number. Why it is wrong: Floating point gives 0.30000000000000004. Instead: Calculate on the server with decimal, or use integer cents.
  • Mistake: Turning off 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.
  • Mistake: Overusing any. Why it is wrong: It switches off checking and spreads silently. Instead: Use unknown and narrow.
  • Mistake: Passing this.method as a callback. Why it is wrong: this becomes undefined when called. Instead: Use arrow functions or .bind.
  • Mistake: Firing promises without 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions generating types from OpenAPI Why: Checks they can stop contract drift between backend and frontend
    How to answer

    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.

  2. When: Candidate compares AbortSignal with CancellationToken Why: Checks they understand cooperative cancellation on the .NET side too
    How to answer

    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.

↩ Usually asked after

More in Web Basics

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me