乐闻世界logo
搜索文章和话题

Can you tell the names of some of the built-in types in TypeScript?

1个答案

1

TypeScript includes numerous built-in types that assist developers in defining the types of variables, function parameters, and return values, thereby ensuring code safety and reliability. Here are some common examples of TypeScript's built-in types:

  1. Basic Types:
  • number: Represents numeric values, treating integers and floating-point numbers interchangeably. Example: let age: number = 30;
  • string: Represents string values. Example: let name: string = "Alice";
  • boolean: Represents boolean values, with only true and false. Example: let isValid: boolean = true;
  • void: Used for functions that do not return a value. Example: function logMessage(): void { console.log("Hello!"); }
  • undefined and null: JavaScript's basic types, also usable as types in TypeScript.
  1. Composite Types:
  • Array: Represents arrays where all elements share the same type. It can be expressed as number[] or Array<number>. Example: let list: number[] = [1, 2, 3];
  • Tuple: Represents an array with a fixed number of elements of specific types, where individual elements may have different types. Example: let person: [string, number] = ["Alice", 30];
  1. Special Types:
  • any: Represents any type, commonly used when a variable's specific type is not specified, though it bypasses type checking. Example: let notSure: any = 4;
  • unknown: Similar to any, but safer as it requires explicit type checking before operations. Example: let value: unknown = 30;
  • never: Represents values that never exist. It is used for functions that never return (e.g., by throwing an exception or entering an infinite loop). Example: function error(message: string): never { throw new Error(message); }
  1. Enum Types (enum):
  • Enables defining a set of named constants. Enums provide clarity in expressing intent or creating distinct cases. Example:
typescript
enum Color {Red, Green, Blue} let c: Color = Color.Green;

Utilizing these types enhances code maintainability and readability, and helps prevent common errors through compile-time type checking.

2024年7月29日 13:23 回复

你的答案