mobile wallpaper 1mobile wallpaper 2mobile wallpaper 3mobile wallpaper 4
428 words
2 minutes
Getting Started with TypeScript
2024-11-04

TypeScript Basics#

  • Type System: Type declarations for variables and functions (e.g., string, number, boolean etc).
  • Interfaces: How to define data structures using interfaces.
  • Classes: Understand class definitions and usage, including constructors and methods.
  • Decorators: In Angular, components, modules, etc. are defined using decorators, such as @Component, @NgModule etc.

1. Basic Types#

TypeScript supports the following common primitive types:

  • number: numeric type, including integers and floating-point numbers.

    let age: number = 30
  • string: string type, used to store text.

    let name: string = "Alice";
  • boolean: boolean type, values are true or false.

    let isActive: boolean = true;
  • array: array type, can specify the element type.

    let numbers: number[] = [1, 2, 3];
  • tuple: tuple type, for fixed-length arrays with specified types.

    let user: [string, number] = ["Alice", 30]
  • enum: enumeration type, defines a set of named constants.

    enum Color { Red, Green, Blue }
    let color: Color = Color.Green;
  • any: any type, suitable for variables of uncertain type, but not recommended to use frequently.

    let randomValue: any = "hello";
    randomValue = 5; // can be reassigned to other types
  • void: no return value, typically used for functions that do not return a value.

    function logMessage(): void {
    console.log("This is a message");
    }
  • null and undefined: represent empty or undefined variables.

    let u: undefined = undefined;
    let n: null = null;

2. Type Annotations#

You can add type annotations to variables, parameters, and return values to aid code completion and error checking.

let name: string = "Alice";
function greet(name: string): string {
return `Hello, ${name}`;
}

3. Interfaces#

Interfaces are used to define the structure of objects (i.e., which properties and methods they have), helping to achieve code reuse and flexibility.

interface Person {
name: string;
age: number;
greet(): string;
}
let alice: Person = {
name: "Alice",
age: 30,
greet() {
return `Hello, my name is ${this.name}`;
}
};

4. Classes#

TypeScript supports object-oriented programming, allowing the use of classes and inheritance. Classes include constructors, properties, and methods.

class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
move(distance: number = 0) {
console.log(`${this.name} moved ${distance} meters.`);
}
}
let dog = new Animal("Dog");
dog.move(10);
  • Access Modifiers

TypeScript provides three access modifiers to control the accessibility of class members:

  • public: public, the default modifier; accessible anywhere.
  • private: private; only accessible within the class.
  • protected: protected; accessible within the class and in subclasses.
class Person {
public name: string;
private age: number;
protected address: string;
constructor(name: string, age: number, address: string) {
this.name = name;
this.age = age;
this.address = address;
}
}

5. Generics#

Generics allow defining functions, classes, or interfaces without specifying a type, and specify the type at use time. This increases code reuse.

function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("Hello"); // T inferred as string

6. Type Inference#

TypeScript automatically infers the type of variables from the code; if no explicit type is declared, TypeScript infers it from the assigned value.

let x = 10; // TypeScript automatically infers x as number

7. Union Types#

Union types allow a variable to hold multiple types of values, defined using the | symbol.

let value: string | number;
value = "Hello";
value = 42;

8. Type Aliases#

Use the type keyword to define type aliases for reuse.

type ID = string | number;
let userId: ID = "123";

9. Type Assertions#

Type assertions tell the compiler the specific type of a value, useful when we know more about the variable than TypeScript does.

let someValue: any = "This is a string";
let strLength: number = (someValue as string).length;

10. Decorators#

Decorators are an advanced feature in TypeScript that allow attaching metadata to classes, methods, or properties. Decorators are heavily used in Angular to define components, modules, etc.

function log(target: any, key: string) {
console.log(`${key} was called`);
}
class Person {
@log
greet() {
console.log("Hello!");
}
}

11. Modules and Namespaces#

  • Modules: TypeScript supports the ES6 module system; modules can be imported and exported using import and export.
module.ts
export const pi = 3.14;
// main.ts
import { pi } from './module';
console.log(pi);
  • Namespaces: TypeScript provides namespaces to organize code, suitable for large applications.
namespace Geometry {
export function calculateArea(radius: number): number {
return Math.PI * radius * radius;
}
}
console.log(Geometry.calculateArea(5));
Share

If this article helped you, please share it with others!

Getting Started with TypeScript
https://dreaife.tokyo/en/posts/ts-basics-learn/
Author
dreaife
Published at
2024-11-04
License
CC BY-NC-SA 4.0

Some information may be outdated

Related Posts Smart
1
Angular-based Anime Showcase Website + Login/Registration (Cognito)
FRONTEND This project is an Angular-based web application for displaying and searching anime on Bangumi, with Cognito for user authentication. It supports automatic deployment to GitHub Pages using GitHub Actions for automated build and deployment. The main tech stack includes Angular 16, TypeScript, HTML, and CSS, and the project includes features such as login, registration, search, and an anime calendar.
2
Bidding Platform Based on Nest.js and Angular, with Jest Tests and CI/CD
BACKEND This project is a bidding platform built with Nest.js and Angular, providing features such as user registration, project management, and bid management. It uses PostgreSQL as the database and Swagger to generate API documentation. The backend implements secure authentication with AWS Cognito, while the frontend provides a user-friendly interface for project display and bid management. The project uses Jest for testing to ensure code quality and GitHub Actions for continuous integration and deployment.
3
Java Atomic Classes and Common Concurrent Containers
cs-base This article introduces Java atomic classes and common concurrent containers, including atomic classes for primitive types (such as AtomicInteger, AtomicLong, and AtomicBoolean), atomic array classes, atomic reference classes, and atomic field updater classes. It also explains the features and usage scenarios of concurrent containers such as ConcurrentHashMap, CopyOnWriteArrayList, ConcurrentLinkedQueue, BlockingQueue, and ConcurrentSkipListMap.
4
Java IO
cs-base Java IO covers the basic concepts of input and output streams, including the classification of byte streams and character streams and their common classes such as InputStream, OutputStream, Reader, and Writer. Byte streams are used for raw byte data, while character streams are used for character data. Buffered streams improve performance by reducing the number of IO operations. Adapter and decorator patterns are widely used in Java IO streams to enhance functionality and coordinate different interfaces. Java IO models include synchronous blocking IO, non-blocking IO, and asynchronous IO, each suited to different scenarios.
5
Java Collections Overview
cs-base Java collections are mainly derived from the Collection and Map interfaces and include subinterfaces such as List, Set, and Queue. List stores ordered duplicate elements, Set stores unique elements, Queue stores elements in a specific order, and Map stores key-value pairs. Collection choices should match requirements such as thread safety and sorting. Java collections provide flexible data storage methods and multiple operations, often more suitable than arrays. The article also compares ArrayList vs. LinkedList for insertion and deletion performance, and HashMap vs. Hashtable for thread safety and efficiency, while noting that ConcurrentHashMap provides better concurrency support.

Table of Contents