teach me typescript
- User
teach me typescript
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
teach me typescript
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Let's start with an introduction to TypeScript and then build up from the basics to more advanced topics. TypeScript is a statically-typed superset of JavaScript, which means that any valid JavaScript is also valid TypeScript. It adds optional static typing, classes, and interfaces, among other features, which can help you build more robust and scalable applications.
Below is a progressive guide to help you learn TypeScript.
Before you write TypeScript, you need to install it. The easiest way is via npm (Node Package Manager). Make sure you have Node.js installed, then open your terminal and run:
npm install -g typescript
This installs the TypeScript compiler (tsc). You can verify the installation by running:
tsc --version
Create a file named hello.ts with the following content:
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet("World"));
Here, you see:
name is explicitly typed as a string.greet is explicitly declared as a string.To compile the TypeScript code to JavaScript, run:
tsc hello.ts
This will generate a hello.js file. You can execute it with:
node hello.js
TypeScript has several built-in types:
boolean
let isDone: boolean = true;
number
let age: number = 30;
string
let username: string = "Alice";
Arrays can be typed in two ways:
let list: number[] = [1, 2, 3];
let anotherList: Array<number> = [4, 5, 6];
Tuples allow you to express an array with a fixed number of elements and known types:
let tuple: [string, number];
tuple = ["hello", 10]; // Correct
// tuple = [10, "hello"]; // Error: wrong order
Enums allow you to define a set of named constants:
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
anyWhen you need to opt-out of type checking, you can use any:
let notSure: any = 4;
notSure = "maybe a string instead";
notSure = false;
You can define function parameter types and return types:
function add(x: number, y: number): number {
return x + y;
}
let sum = add(3, 4); // sum is of type number
Optional and default parameters are also supported:
// Optional parameter (denoted by ?)
function buildName(firstName: string, lastName?: string): string {
return lastName ? `${firstName} ${lastName}` : firstName;
}
// Default parameter
function buildGreeting(firstName: string, greeting: string = "Hello"): string {
return `${greeting}, ${firstName}!`;
}
Interfaces allow you to define contracts within your code. They define the structure of an object:
interface Person {
firstName: string;
lastName: string;
age?: number; // Optional property
}
function printPerson(person: Person): void {
console.log(`${person.firstName} ${person.lastName}`);
}
printPerson({ firstName: "John", lastName: "Doe" });
Interfaces are also powerful for defining function types:
interface SearchFunc {
(source: string, subString: string): boolean;
}
let mySearch: SearchFunc;
mySearch = function(source: string, subString: string): boolean {
return source.indexOf(subString) !== -1;
};
TypeScript supports modern JavaScript features like classes and inheritance—with the added benefit of type annotations.
class Animal {
private name: string;
constructor(name: string) {
this.name = name;
}
public move(distanceInMeters: number): void {
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
class Dog extends Animal {
constructor(name: string) {
super(name);
}
bark(): void {
console.log("Woof! Woof!");
}
}
const dog = new Dog("Buddy");
dog.bark();
dog.move(10);
public, private, and protected help ensure that your classes encapsulate data appropriately.Generics allow you to write code that works with any data type while still maintaining type safety:
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString"); // output1 is of type string
let output2 = identity<number>(100); // output2 is of type number
Generics are not just limited to functions—you can also create generic classes and interfaces.
Modules help in organizing code. Use the export and import keywords:
greetings.ts
export function sayHello(name: string): string {
return `Hello, ${name}!`;
}
app.ts
import { sayHello } from "./greetings";
console.log(sayHello("TypeScript"));
To compile, you might want to use the --module flag, or set up a tsconfig.json file.
Namespaces provide a way to logically group code (older style before ES6 modules):
namespace Geometry {
export function areaOfSquare(side: number): number {
return side * side;
}
}
console.log(Geometry.areaOfSquare(5));
tsconfig.jsonWhen your project grows, it’s useful to have a configuration file to manage the TypeScript compiler options. Create a tsconfig.json file in your project root:
{
"compilerOptions": {
"target": "es5", // Target JavaScript version
"module": "commonjs", // Module system
"strict": true, // Enable all strict type-checking options
"esModuleInterop": true // Import compatibility for CommonJS modules
},
"include": [
"./src/**/*"
],
"exclude": [
"node_modules"
]
}
Compile your entire project by simply running:
tsc
Official Documentation:
Check out the TypeScript Handbook for in-depth explanations and examples.
Practice:
Try rewriting a small JavaScript project in TypeScript to practice these concepts.
Tooling:
Consider using an editor like Visual Studio Code which has excellent TypeScript support.
Community Tutorials and Courses:
Look for courses on platforms like Udemy, Pluralsight, or freeCodeCamp to get more hands-on practice.
This guide has covered the basics of TypeScript from installation to core language features such as types, interfaces, classes, generics, and modules. By integrating TypeScript into your development workflow, you can write more maintainable and error-resistant code. Feel free to ask more specific questions as you explore and build projects with TypeScript!