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:
- 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 onlytrueandfalse. Example:let isValid: boolean = true;void: Used for functions that do not return a value. Example:function logMessage(): void { console.log("Hello!"); }undefinedandnull: JavaScript's basic types, also usable as types in TypeScript.
- Composite Types:
Array: Represents arrays where all elements share the same type. It can be expressed asnumber[]orArray<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];
- 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 toany, 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); }
- Enum Types (
enum):
- Enables defining a set of named constants. Enums provide clarity in expressing intent or creating distinct cases. Example:
typescriptenum 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 回复