Welcome to the world of TypeScript! TypeScript is a superset of JavaScript that adds static types and other features to help developers write more robust, maintainable, and scalable code. This tutorial will cover the core syntax of TypeScript, providing you with a solid foundation to start building applications.
TypeScript compiles down to plain JavaScript, which means any valid JavaScript code is also valid TypeScript code. However, TypeScript introduces additional syntax and type-checking features that help catch errors at compile time rather than runtime.
At its core, TypeScript extends JavaScript by adding static types. This means you can specify the data type of variables, function parameters, and return values. Here are some key concepts:
:) followed by the type name.number, string, boolean, null, undefined, and any.Let's dive into some practical examples to illustrate these concepts.
You can specify types for variables using type annotations:
1let age: number = 25;2let name: string = "Alice";3let isStudent: boolean = true;
In this example, age is a number, name is a string, and isStudent is a boolean.
TypeScript supports several basic types:
1let num: number = 10;2let str: string = "Hello";3let bool: boolean = false;4let nul: null = null;5let und: undefined = undefined;6let anyValue: any = "This can be anything";
Arrays can be typed to hold elements of a specific type:
1let numbers: number[] = [1, 2, 3, 4];2let names: string[] = ["Alice", "Bob", "Charlie"];
Tuples allow you to express an array with a fixed number of elements whose types are known:
1let person: [string, number] = ["Alice", 25];
In this example, person is a tuple where the first element is a string and the second element is a number.
Interfaces define the shape of objects:
1interface Person {2name: string;3age: number;4}56let alice: Person = { name: "Alice", age: 25 };
In this example, Person is an interface that defines an object with a name property of type string and an age property of type number.
TypeScript supports ES6 classes:
1class Animal {2name: string;34constructor(name: string) {5this.name = name;6}78speak() {9console.log(`${this.name} makes a noise.`);10}11}1213let dog = new Animal("Dog");14dog.speak();
In this example, Animal is a class with a constructor and a method. The speak method logs a message to the console.
Now that you have a good understanding of TypeScript syntax, the next step is to explore more advanced features such as Variables in TypeScript. This will help you dive deeper into how TypeScript handles variables and their types.
Stay tuned for more tutorials on TypeScript!