TypeScript Basic Structure

The basic structure of a TypeScript program can be divided into several parts, each with a specific purpose.

The following are the common components of a TypeScript program:

  • Declarations: including type declarations, interface declarations, etc.
  • Variable Declarations: includinglet, constandvarthe use of.
  • Function Declarations: including regular functions and arrow functions.
  • Class Declarations: used to define classes and their members.
  • Interfaces & Type Aliases: describe the structure of types.
  • Modularization: throughimportandexportorganize code.
  • Type Assertions: forced type conversion.
  • Generics: make code more reusable.
  • Comments: increase code readability.
  • Type Inference: automatically infers types.
  • Type Guards: narrow the type scope.
  • Asynchronous Programming: supportsasync/await。
  • Error Handling: throughtry/catchto catch errors.

The above parts together form the basic structure of a TypeScript program, providing developers with powerful type checking, code structure, and maintainability.


1. Declarations

Type declarations:TypeScript is a statically typed language that uses type declarations to define the types of variables, functions, classes, and more. Type declarations help make code more maintainable and readable.

Example

let name: string = "Alice";
let age: number = 30;

Interface declarations:Used to define the structure of an object, including its properties and methods.

Example

interface Person {
    name: string;
    age: number;
}

2. Variable Declarations

In TypeScript, you can use let, const, and var to declare variables. It is recommended to use let and const; var is no longer recommended.

Example

let age: number = 25;
const pi: number = 3.14;

3. Function Declarations

Function declarations: TypeScript allows declaring functions with type annotations, including parameter types and return types.

Example

function greet(name: string): string {
    return "Hello, " + name;
}

Arrow functions:TypeScript also supports ES6 arrow functions, using concise syntax to declare functions.

Example

const greet = (name: string): string => "Hello, " + name;

4. Class Declarations

TypeScript provides support for object-oriented programming, allowing you to define classes and their methods and properties.

Example

class Person {
    name: string;
    age: number;
   
    constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
    }
   
    greet() {
    return `Hello, my name is ${this.name}`;
    }
}

5. Interfaces & Type Aliases

Interface: used to describe the shape of an object; interfaces can be inherited and extended.

Example

interface Animal {
    name: string;
    sound: string;
    makeSound(): void;
}

Type Alias:Allows defining aliases for object types, union types, intersection types, and more.

Example

type ID = string | number;

6. Modules & Imports/Exports

TypeScript supports modular programming; you can use import and export to organize code.

Export:

Example

export class Person {
    constructor(public name: string) {}
}

Import:

Example

import { Person } from './person';

7. Type Assertions

In some cases, TypeScript cannot infer the exact type of a variable; developers can use type assertions to explicitly specify the type.

Example

let value: any = "hello";
let strLength: number = (value as string).length;

8. Generics

Generics allow you to avoid specifying concrete types when defining functions, interfaces, or classes, instead using placeholders that let users pass in specific types when using them. Generics increase code reusability and type safety.

Example

function identity<T>(arg: T): T {
    return arg;
}

9. Comments

Comments are used in TypeScript programs to explain the purpose and logic of code, increasing readability.

Single-line comments:

Example

// This is a single-line comment

Multi-line comments:

Example

/* This is a
multi-line comment */


10. Type Inference

TypeScript automatically infers the type of a variable in certain situations. For example, when declaring a variable and assigning a value, TypeScript infers the variable's type.

Example

let num = 10;  // TypeScript infers that num is of type number

11. Type Guards

TypeScript provides type guards (such as typeof and instanceof) to narrow the type range of variables at runtime.

Example

function isString(value: any): value is string {
    return typeof value === 'string';
}

12. Asynchronous Programming

TypeScript fully supports asynchronous programming; you can use async/await syntax to handle asynchronous operations.

Example

async function fetchData(): Promise<string> {
    const response = await fetch("https://example.com");
    const data = await response.text();
    return data;
}

13. Error Handling

TypeScript allows error handling with try/catch blocks, and you can also use types to describe error types.

Example

try {
    throw new Error("Something went wrong");
} catch (error) {
    if (error instanceof Error) {
        console.error(error.message);
    }
}
Other Extensions