Full answer
TypeScript (TS) is a superset of JavaScript: valid JavaScript is valid TypeScript, with additional syntax for types. A compiler (tsc) or a tool such as esbuild, Babel, or SWC checks or removes the type syntax, and the result runs on any JavaScript engine. Recent Node.js versions can also run simple TypeScript files directly by removing the types, without checking them.
What it adds:
- Static types: annotate variables, parameters, and return values. The compiler reports errors such as passing a string where a number is expected, reading a property that does not exist, or forgetting to handle
undefined. - Inference: you often do not write types, because the compiler infers them from values.
- Interfaces and type aliases, generics, unions (
string | number), literal types, and narrowing: afterif (typeof x === 'string'), the compiler knows the type inside the block. - Better editor tooling: autocomplete, safe renames, and go to definition.
- A few runtime features, such as
enum, which compile to real JavaScript. Many teams avoidenumand use unions of literals.
What it does not do: types are erased, so there is no runtime check. An as cast only tells the compiler to trust you. JSON.parse returns any, and a typed API response can still be wrong at runtime. Validate external data with a schema library or manual checks, and use the type system for the code you control.
Other points that interviewers ask about: any turns checking off for a value, and unknown forces you to check before use. A strict setting enables the most helpful checks and is the recommended starting point. TypeScript adds a build step and a learning cost, but it pays off in larger code bases and teams. JavaScript with JSDoc comments and checkJs can get part of the same checking without a build step.
Answer carefully when asked whether TypeScript is better: it helps with maintainability and refactoring, it does not remove the need for tests, and it does not make code faster.
const ts = require('typescript');
const source = `
interface User { name: string; age: number }
function greet(user: User, times: number): string {
return ('Hello ' + user.name + ' ').repeat(times).trim();
}
enum Color { Red, Green }
const parsed = JSON.parse('{"name":"Asha","age":"31"}') as User;
`;
// 1. Types are erased: the output is plain JavaScript
const output = ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
console.log(output.trim());
// 2. Type checking happens before running, with an in-memory file
function check(code) {
const options = { strict: true, noEmit: true, target: ts.ScriptTarget.ES2022, lib: ['lib.es2022.d.ts'], types: [] };
const host = ts.createCompilerHost(options);
const original = host.getSourceFile.bind(host);
host.getSourceFile = (file, languageVersion) =>
file === 'input.ts' ? ts.createSourceFile(file, code, languageVersion) : original(file, languageVersion);
host.fileExists = (file) => file === 'input.ts' || ts.sys.fileExists(file);
host.readFile = (file) => (file === 'input.ts' ? code : ts.sys.readFile(file));
const program = ts.createProgram(['input.ts'], options, host);
return ts.getPreEmitDiagnostics(program).map((d) => {
const { line } = d.file.getLineAndCharacterOfPosition(d.start);
return `line ${line + 1}: ${ts.flattenDiagnosticMessageText(d.messageText, ' ')}`;
});
}
console.log('--- valid code');
console.log(check(source + 'greet({ name: "Ben", age: 2 }, 2);'));
console.log('--- type errors found before running');
console.log(check(source + 'greet({ name: "Ben" }, "2");'));
console.log(check('function first(items: string[]) { return items[0].toUpperCase(); }\nfirst(42);'));
// 3. The cast above compiled, but the data is wrong at runtime
const parsed = JSON.parse('{"name":"Asha","age":"31"}');
console.log('typeof age at runtime:', typeof parsed.age, '(declared as number in the TypeScript source)');
console.log('TypeScript version used:', ts.version);Run with Node.js v24.22.1 as js-130.js; two runs gave identical output. Output: function greet(user, times) { return ('Hello ' + user.name + ' ').repeat(times).trim(); } var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; })(Color || (Color = {})); const parsed = JSON.parse('{"name":"Asha","age":"31"}'); --- valid code [] --- type errors found before running [ "line 8: Argument of type '{ name: string; }' is not assignable to parameter of type 'User'. Property 'age' is missing in type '{ name: string; }' but required in type 'User'." ] [ "line 2: Argument of type 'number' is not assignable to parameter of type 'string[]'." ] typeof age at runtime: string (declared as number in the TypeScript source) TypeScript version used: 5.9.3
Key points
- TypeScript is JavaScript plus static types; the compiler checks them and then erases them.
- It catches wrong types, missing properties, and unhandled undefined, and improves editor support.
- No runtime checks: casts are trust, and external data needs validation.
- any disables checks, unknown forces narrowing; start with strict mode.
- It adds a build step; it does not replace tests or improve speed.
Common mistakes
- Believing that types are checked at runtime.
- Using as casts or any to silence errors instead of fixing the type or validating data.
- Trusting the type of JSON from an API without validation.
- Expecting TypeScript to remove the need for tests.
Follow-ups
- What is the difference between any and unknown?
- How do you validate untrusted data and keep the types in sync with the validation?
- What is type narrowing, and how does a discriminated union use it?
Tips
- Lead with "types are erased" and explain the consequences.
- Mention validation for external data and the strict setting.
- Be balanced: TypeScript helps maintenance and tooling but is not a substitute for tests.