Home > Article > Web Front-end > A Journey to Learn Typescript.
Hi everyone, I recently began my TypeScript journey and have been making progress through Programming Hero's advanced web development course. I had some basic knowledge of TypeScript but hadn't explored it in depth. My course started with a deep dive into TypeScript. A week has passed, and I've made significant progress in my learning. Here's a simplified overview of the key concepts I've grasped.
TypeScript is a superset of JavaScript that adds optional static typing to the language. This means you can declare the types of variables, function parameters, and return values, which can help catch potential errors early in the development process.
Benefits of Using TypeScript
Primitive data types represent single values and are stored directly in memory. here are some of the primitive data types used in typescript
let name : string = "Kishor"; let age : number = 27; let isDeveloper: boolen = true; let x : null = null; let y: undefined = undefined;
as you can see in the example to assign a type to a variable you have to use the colon ( : ) symbol after defining the variable name and then the type.
Non-Primitive data types, also known as reference types, represent complex data structures and are stored as references to memory locations. TypeScript supports the following non-primitive data types:
let Person: {name: string, age : number} = {name: "kishor", age: 27}; //object let numbers: number[] = [1,2,3,4]; let fruits: string[]= ["apple", "pineapple", "banana"]; let tuple: [string, number, boolean] = ["xyz", 123, true]; function greet(name: string) : any { return `hello ${name}` }
A type alias in TypeScript is a way to give a new name to an existing type. This can make your code more readable and maintainable, especially when dealing with complex types.
// Defining a type alias for a person object type Person = { name: string; age: number; }; // Using the type alias const person1: Person = { name: "Alice", age: 30 };
In this example, Person is a type alias that represents an object with name and age properties.
Union and Intersection Types in TypeScript
A union type represents a value that can be one of several types. It's defined using the | operator.
An intersection type combines multiple types into a single type. It's defined using the & operator.
type StringOrNumber = string | number; //Union type let value: StringOrNumber = "hello"; value = 42; type Person = { name: string; age: number; }; type Address = { street: string; city: string; }; type PersonWithAddress = Person & Address;//Intersection type const personWithAddress: PersonWithAddress = { name: "Alice", age: 30, street: "123 Main St", city: "Anytown" };
The never type represents values that never occur.
The unknown type represents any value. It's safer than the any type because you must perform type checks or assertions before using a value of type unknown.
let name : string = "Kishor"; let age : number = 27; let isDeveloper: boolen = true; let x : null = null; let y: undefined = undefined;
Type assertion is a way to tell the TypeScript compiler that you know more about a type than it does. It's a way to explicitly specify the type of a variable
let Person: {name: string, age : number} = {name: "kishor", age: 27}; //object let numbers: number[] = [1,2,3,4]; let fruits: string[]= ["apple", "pineapple", "banana"]; let tuple: [string, number, boolean] = ["xyz", 123, true]; function greet(name: string) : any { return `hello ${name}` }
Type guards allow you to narrow down the type of a variable based on certain conditions. By checking the type of a variable before accessing its properties or methods, you can avoid potential runtime errors.
// Defining a type alias for a person object type Person = { name: string; age: number; }; // Using the type alias const person1: Person = { name: "Alice", age: 30 };
An interface in TypeScript is a blueprint for creating objects with specific properties.
type StringOrNumber = string | number; //Union type let value: StringOrNumber = "hello"; value = 42; type Person = { name: string; age: number; }; type Address = { street: string; city: string; }; type PersonWithAddress = Person & Address;//Intersection type const personWithAddress: PersonWithAddress = { name: "Alice", age: 30, street: "123 Main St", city: "Anytown" };
In this example, the Person interface defines that a person object must have firstName, lastName, and age properties. When creating a person1 object
Generics are a powerful feature in TypeScript that allows you to create reusable components that can work with different data types.
function error(message: string): never { throw new Error(message); } //the return type is never because there is no data returned. let value: unknown = "hello"; if (typeof value === "string") { let strLength: number = value.length; }
In this example, T is a type parameter. It represents a placeholder for any type. When you call the identity function, you can pass any type of argument, and the function will return the same type.
In TypeScript, generic constraints allow you to apply limitations on the types that can be passed as arguments to a generic function or used as type parameters in a generic class or interface.
let value: unknown = "hello"; let strLength: number = (value as string).length;
here the extends keyword is used to constrain the data
The keyof operator in TypeScript is used to get a union type of all the property names of an object type. This is particularly useful when working with generic types and mapped types.
//typeof function printValue(value: unknown) { if (typeof value === "string") { console.log(value.toUpperCase()); } else if (typeof value === "number") { console.log(value.toFixed(2)); } } //instanceof function printDate(date: unknown) { if (date instanceof Date) { console.log(date.toISOString()); } }
Pick
interface Person { firstName: string; lastName: string; age: number; } const person1: Person = { firstName: "Alice", lastName: "Johnson", age: 30 };
Omit
function identity<T>(arg: T): T { return arg; } identity<string>(string);
Partial
interface Person { name: string; age: number; } function identity<T extends Person>(arg: T): T { return arg; } const result = identity<Person>({ name: "aa"; age: 12; });
others like,
Required
Readonly
Record
In TypeScript, classes are defined using the class keyword.
interface Person { name: string; age: number; } type PersonKeys = keyof Person; // Type: "name" | "age"
public The default visibility of class members is public. A public member can be accessed anywhere
protected members are only visible to subclasses of the class they're declared in.
private Members are accessible only within the class.
Static members in TypeScript are members (properties and methods) that belong to the class itself, rather than to individual instances of the class.
let name : string = "Kishor"; let age : number = 27; let isDeveloper: boolen = true; let x : null = null; let y: undefined = undefined;
In TypeScript, interfaces define a contract for classes to implement. A class that implements an interface must have all the properties and methods declared in the interface. The implements keyword is used
let Person: {name: string, age : number} = {name: "kishor", age: 27}; //object let numbers: number[] = [1,2,3,4]; let fruits: string[]= ["apple", "pineapple", "banana"]; let tuple: [string, number, boolean] = ["xyz", 123, true]; function greet(name: string) : any { return `hello ${name}` }
Those are some of the basic use cases of Typescript that I learned this week. I've learned a bunch of cool stuff, but there's still so much more to discover. TypeScript is constantly evolving, so I am trying to keep up with the latest releases and features and following TypeScript's official documentation and blog for the latest news and best practices.
Thanks for keeping up with me on my journey.
The above is the detailed content of A Journey to Learn Typescript.. For more information, please follow other related articles on the PHP Chinese website!