Introduction to TypeScript Playground
The TypeScript Playground is a TypeScript sandbox r where you can write, share, and try out TypeScript online without installing anything. It's a great way to learn and explore TypeScript features.
// Welcome to TypeScript Playground
const greeting: string = "Hello, TypeScript Playground!";
console.log(greeting);
Exploring TypeScript Features
The TypeScript Playground works similarly to a TypeScript REPL and is ideal for testing various TypeScript features like union types, type guards, and type inference. These features help you write better and more reliable code.
Union Types
Typescript union types let you use multiple types in one variable. This is useful when dealing with different data types in a single variable.
type StringOrNumber = string | number;
const value: StringOrNumber = 'hello';
Type Guards
Type guards are functions that determine the type of a value in a certain scope, helping to prevent type errors and make your code safer.
function isString<T>(value: T): value is string {
return typeof value === 'string';
}
const value: string | number = 'hello';
if (isString(value)) {
console.log(value.toUpperCase());
}
Type Inference
Type inference is when TypeScript figures out the type of a variable based on how you use it, saving you time and effort in coding.
const numbers = [1, 2, 3];
// TypeScript infers the type of numbers as number[]
Testing TypeScript Code Online
With the TypeScript Playground, you can test your TypeScript code online without setting up a local environment. It's great for quick prototyping and experimentation. Check out our TypeScript best practices when testing Convex functions.
Starting a New Playground
To begin a new project, visit the TypeScript Playground website and start typing your code. You can also use an example template from the menu to get started.
// Shopping cart total calculator
interface CartItem {
name: string;
price: number;
quantity: number;
}
function calculateTotal(items: CartItem[]) {
return items.reduce((sum, item) => sum + (item.price * item.quantity), 0);
}
const cart: CartItem[] = [
{ name: "T-shirt", price: 15, quantity: 2 },
{ name: "Shoes", price: 50, quantity: 1 }
];
console.log(`Total: $${calculateTotal(cart)}`); // Total: $80
Sharing Code Examples
The TypeScript Playground makes sharing your code simple. You can create a shareable link or export your code as a TypeScript file.
Creating a Shareable Link
To create a shareable link, click the "Share" button and copy the link. The playground automatically includes your code, compiler settings, and any dependencies in the shared URL. This ensures others see your code exactly as you intended. Learn how we handle TypeScript at Convex to write more shareable code.
// Share this code snippet with others
// A reusable sorting utility
function sortByProperty<T>(array: T[], property: keyof T) {
return [...array].sort((a, b) =>
a[property] < b[property] ? -1 :
a[property] > b[property] ? 1 : 0
);
}
// Example usage
const users = [
{ name: "Charlie", age: 30 },
{ name: "Alice", age: 25 },
{ name: "Bob", age: 35 }
];
console.log(sortByProperty(users, "name"));
console.log(sortByProperty(users, "age"));
Debugging Code Snippets
The TypeScript Playground includes a built-in debugger to help you find errors in your code. You can set breakpoints, step through code, and inspect variables as your program runs.
Using the Debugger
To use the debugger, set breakpoints by clicking the line numbers, then use the debug controls to step through your code and check variable values.
// Example of debugging
class TaskManager {
private tasks: string[] = [];
addTask(task: string) {
this.tasks.push(task);
return this.tasks.length;
}
getTask(index: number) {
return this.tasks[index];
}
listTasks() {
return [...this.tasks];
}
}
const manager = new TaskManager();
manager.addTask("Write documentation");
manager.addTask("Test code");
console.log(manager.listTasks());
Exploring Compiler Options
The TypeScript Playground lets you explore different compiler settings, such as the target JavaScript version and module system.
Setting Compiler Options
To adjust compiler settings, click the "Settings" button and select the "Compiler Options" tab. Common options include strict mode, target ECMAScript version, and module type. Pick your options to customize how your code is compiled.
// Example of changing target version
// Change the target to ES5 or ES6 in the Playground settings
let version: string = "ES6 features enabled";
console.log(version);
Converting JavaScript Code to TypeScript
The TypeScript Playground includes tools to convert JavaScript code into TypeScript. This helps you migrate existing code or learn how TypeScript adds type safety to JavaScript.
Converting JavaScript to TypeScript
Paste your JavaScript code into the playground, and it will suggest type annotations and interfaces based on your code's structure. You can then refine these types to match your needs.
// Original JavaScript
function greet(name) {
console.log(`Hello, ${name}!`);
}
// Adding TypeScript features
function greet(name: string) {
console.log(`Hello, ${name}!`);
}
// Using the typed function
greet("Alice"); // Works
greet(123); // TypeScript will show an error
Visualizing Type Checking
The TypeScript Playground helps you see type checking in action, which can clarify how TypeScript's type system works and spot type errors.
Understanding Type Checking
The playground shows type errors inline and provides hover information about types. This visual feedback helps you learn how TypeScript's type system works.
// Example of type checking
let age: number = 25;
// Uncommenting the line below will show a type error in real-time
// age = "twenty-five";
Final Thoughts on TypeScript Playground
The TypeScript Playground is an essential tool for writing, testing, and sharing TypeScript code. Its real-time type checking, compiler options, and instant feedback make it perfect for learning TypeScript features, prototyping code, or quickly testing ideas.