Online TypeScript Compiler
index.ts
Ready
About TypeScript
TypeScript is JavaScript with types. The compiler checks your types first, then runs the JavaScript it produces on Node.js.
How to take input in TypeScript
Read standard input with fs.readFileSync(0), then split and convert it, adding types as you go.
const input: string = require("fs").readFileSync(0, "utf8").trim();
const nums: number[] = input.split(" ").map(Number);TypeScript programs to try
Copy one into the editor above, put any input in the Input tab and press Run.
An interface and a typed function
interface Student { name: string; marks: number; }
function topper(list: Student[]): Student {
return list.reduce((best, s) => (s.marks > best.marks ? s : best));
}
const students: Student[] = [
{ name: "Asha", marks: 91 },
{ name: "Ravi", marks: 86 },
];
console.log(topper(students).name);A generic function
function last<T>(items: T[]): T | undefined {
return items[items.length - 1];
}
console.log(last([1, 2, 3]));
console.log(last(["a", "b"]));Union types
type Id = number | string;
function show(id: Id): string {
return typeof id === "number" ? `#${id}` : id.toUpperCase();
}
console.log(show(7), show("abc"));Common TypeScript errors and how to fix them
- error TS2322: Type 'string' is not assignable to type 'number'
- A value doesn't match the declared type. Convert it (for example Number(x)) or fix the type.
- error TS2304: Cannot find name 'x'
- The name is misspelled or not declared in this scope.
- error TS2532: Object is possibly 'undefined'
- Check the value first (if (x) ...) or give it a default before using it.
Frequently asked questions
Is this online TypeScript compiler free?
Yes. Write and run TypeScript code in your browser for free, with nothing to install and no setup.
How do I give input to my TypeScript program?
Type it in the Input tab before pressing Run and read it with require("fs").readFileSync(0, "utf8").
Will type errors stop my program?
Yes. TypeScript checks the code first, and type errors are shown in the output so you can fix them.
Does it work on my phone?
Yes. The editor, input and output work in a mobile browser, so you can practise TypeScript without a laptop.