TypeScript types

1. Type

  1. basic type:

    • number: Represents numeric types, including integers and floating-point numbers.
    • string: Indicates the string type.
    • boolean: Represents a Boolean type with only two possible values: trueor false.
    • nulland undefined: represent null value and undefined value respectively.
    • symbol: Represents a unique, immutable value, used as a property of an object.
    • bigint: Represents an integer of arbitrary precision.
    • 字面量: A literal type is a type represented by directly specifying a specific literal value.
  2. Composite type:

    • array: Indicates an array type, which can contain multiple elements, and each element can have the same or different types.
    • object: Indicates the object type, which can contain multiple attributes and corresponding values.
    • tuple: Represents the tuple type, which is an array of fixed length and fixed type.
    • enum: Represents an enumeration type, defining a set of named constants.
    • any: Indicates any type, and type checking is canceled.
    • unknown: Represents an unknown type, similar to any, but more type-safe.
    • void: Indicates the return type of a function that does not return a value.
    • never: A type that represents a value that never exists, usually used to represent a code path that throws an exception or cannot be executed.
  3. Other types:

    • union: Represents a union type, where a value can be one of multiple types.
    • intersection: Indicates a cross type, a value has attributes of multiple types at the same time.
    • function: Indicates the function type, including parameter types and return value types.
    • class: Represents the class type, used to create the blueprint of the object.
    • interface: Indicates the interface type, which is used to describe the structure and properties of the object.
    • type: Indicates a custom type alias.
    • readonly: Indicates a read-only property modifier.
    • Partial<T>: Indicates that Tall properties of the type are set to optional.
    • Pick<T, K>: Indicates that a new type is formed Tby selecting specified attributes from the type.K
    • Record<K, T>: Indicates that Ta value of type Kis associated with a key of type to form a new type.

In addition, there are many advanced types and type operators, such as mapped types, conditional types, infer keyword, etc., for more complex type manipulation and derivation.

Two, examples

  1. basic type:
let num: number = 10;
let str: string = "Hello";
let bool: boolean = true;
let n: null = null;
let u: undefined = undefined;
let sym: symbol = Symbol("key");
let big: bigint = BigInt(10);
let stringLiteral: "hello" = "hello";
  1. Composite type:
let arr: number[] = [1, 2, 3];
let obj: object = {
    
     key: "value" };
let tuple: [number, string] = [1, "one"];
enum Color {
    
     Red, Green, Blue }
let c: Color = Color.Green;
let anyValue: any = 5;
let unknownValue: unknown = "unknown";
let voidFunc: () => void = () => {
    
     console.log("Void function"); };
let neverValue: never = (() => {
    
     throw new Error("Error"); })();
  1. Union types and intersection types:
let union: string | number = "hello";
union = 10;

interface A {
    
     a: number }
interface B {
    
     b: string }
type Intersection = A & B;

let obj: Intersection = {
    
     a: 1, b: "two" };
  1. Function type:
function add(x: number, y: number): number {
    
    
  return x + y;
}

let multiply: (x: number, y: number) => number;
multiply = (x, y) => x * y;
  1. class type:
class Person {
    
    
  name: string;
  constructor(name: string) {
    
    
    this.name = name;
  }
}

let person: Person = new Person("Alice");
  1. Interface Type:
interface Point {
    
    
  x: number;
  y: number;
}

let point: Point = {
    
     x: 1, y: 2 };
  1. Advanced types and type operators:
type PartialPoint = Partial<Point>;
let partialPoint: PartialPoint = {
    
     x: 1 };

type PickedPoint = Pick<Point, "x">;
let pickedPoint: PickedPoint = {
    
     x: 1 };

type RecordPoint = Record<string, number>;
let recordPoint: RecordPoint = {
    
     x: 1, y: 2 };

type MappedNumbers = {
    
     [K in "one" | "two"]: number };
let mappedNumbers: MappedNumbers = {
    
     one: 1, two: 2 };

type ReturnTypeFunc = () => string;
let returnTypeFunc: ReturnTypeFunc = () => "Hello";

3. Characteristics

  1. Type Safety (Type Safety): TypeScript emphasizes type safety, which captures potential type errors at compile time through type checking and avoids type-related errors at runtime. This reduces debugging time and improves code quality.

  2. Static Typing: TypeScript is a statically typed language, where type information is determined and remains unchanged at compile time. Variables, function parameters, function return values, etc. all need to declare types, and type checking is performed during compilation.

  3. Type Inference: TypeScript has a type inference function, which can infer the type of a variable based on its assignment, thereby reducing manual type annotations. This makes code writing more concise and flexible, while still maintaining type safety.

  4. Structural Typing: TypeScript's type system is based on structural typing, not nominal typing. This means that types are compared based on their structure rather than their names. As long as two types are structurally similar, they are considered compatible types.

  5. Generics: TypeScript supports generic programming, allowing the use of type parameters in functions, classes, and interfaces. This allows for writing more general and reusable code, making the code more flexible and type-safe.

  6. Type Aliases: TypeScript allows the creation of type aliases, which simplify the representation of complex types by giving the type a new name. Type aliases can improve the readability and maintainability of your code.

  7. Union Types and Intersection Types: TypeScript provides support for Union Types and Intersection Types. Union types indicate that a value can be one of several types, while intersection types indicate that a value has properties of more than one type at the same time.

  8. Type Guards: TypeScript provides a mechanism for type protection, through some syntax and patterns to narrow the type range of variables, so as to obtain more specific types in specific code blocks. This improves code readability and type safety.

  9. Optional Types and Default Values: TypeScript allows marking properties or function parameters as optional and providing default values. This makes it possible to selectively omit certain properties or parameters when using an object or function.

  10. Type Annotations and Type Assertions: TypeScript allows developers to explicitly add type information to variables, function parameters, etc. using type annotations. At the same time, you can also use type assertion to tell the compiler the specific type of a value, so that compile-time type checking can be performed when needed.

4. Details

array

In TypeScript, there are several ways to create array types. The following are some common ways to create array types:

  1. Type suffix notation:
let arr: number[] = [1, 2, 3]; // 数字数组
let strArr: string[] = ["hello", "world"]; // 字符串数组
let boolArr: boolean[] = [true, false]; // 布尔数组
  1. Use a generic array type:
let arr: Array<number> = [1, 2, 3]; // 数字数组
let strArr: Array<string> = ["hello", "world"]; // 字符串数组
let boolArr: Array<boolean> = [true, false]; // 布尔数组
  1. Use tuple types:
let tuple: [number, string, boolean] = [1, "hello", true];
  1. Use type aliases:
type NumberArray = number[];
let arr: NumberArray = [1, 2, 3]; // 数字数组

type StringArray = Array<string>;
let strArr: StringArray = ["hello", "world"]; // 字符串数组

Guess you like

Origin blog.csdn.net/weixin_35691921/article/details/131418519