Introduction to basic type systems
Introduction to the Basic Type System
TypeScript's type system is one of its core features, adding static type-checking capabilities to JavaScript. The type system helps developers identify potential errors during the coding phase, improving code maintainability and readability. TypeScript's type system includes basic types, union types, intersection types, type aliases, interfaces, and more.
Basic Types
TypeScript provides several basic types that correspond to JavaScript's primitive types. These types include:
number
: Represents numbers, including integers and floating-point numbers.string
: Represents strings.boolean
: Represents boolean values,true
orfalse
.null
andundefined
: Represent thenull
andundefined
values, respectively.symbol
: Represents unique symbol values.bigint
: Represents large integers.
let age: number = 25;
let name: string = "Alice";
let isStudent: boolean = true;
let nothing: null = null;
let notDefined: undefined = undefined;
let uniqueSymbol: symbol = Symbol("unique");
let bigNumber: bigint = 100n;
Arrays and Tuples
TypeScript supports array and tuple types for representing ordered collections of values.
- Array types can be defined using
type[]
orArray<type>
. - Tuple types are used to represent arrays with a fixed length and specific types.
// Arrays
let numbers: number[] = [1, 2, 3];
let names: Array<string> = ["Alice", "Bob", "Charlie"];
// Tuples
let person: [string, number] = ["Alice", 25];
let rgb: [number, number, number] = [255, 0, 0];
Union Types and Literal Types
Union types allow a variable to be one of several types, while literal types restrict values to specific literals.
// Union types
let id: string | number = "123";
id = 123; // Valid
// Literal types
let direction: "north" | "south" | "east" | "west" = "north";
direction = "south"; // Valid
// direction = "up"; // Error: Type mismatch
Type Aliases and Interfaces
Type aliases and interfaces are used to define complex type structures.
- Type aliases are defined using the
type
keyword. - Interfaces are defined using the
interface
keyword and support extension and implementation.
// Type alias
type Point = {
x: number;
y: number;
};
let p1: Point = { x: 10, y: 20 };
// Interface
interface Person {
name: string;
age: number;
}
let alice: Person = { name: "Alice", age: 25 };
// Interface extension
interface Employee extends Person {
jobTitle: string;
}
let bob: Employee = { name: "Bob", age: 30, jobTitle: "Developer" };
Enums
Enum types are used to define a set of named constant values.
enum Color {
Red,
Green,
Blue,
}
let c: Color = Color.Green;
console.log(c); // Output: 1
// String enums
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
let d: Direction = Direction.Up;
console.log(d); // Output: "UP"
Type Inference and Type Assertion
TypeScript has powerful type inference capabilities, automatically deducing variable types based on context. Type assertions allow developers to manually specify the type of a value.
// Type inference
let x = 10; // x is inferred as type number
let y = "hello"; // y is inferred as type string
// Type assertion
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
// Or using angle-bracket syntax (not recommended in JSX)
let strLength2: number = (<string>someValue).length;
Function Types
TypeScript allows specifying types for function parameters and return values.
// Function parameter and return types
function add(a: number, b: number): number {
return a + b;
}
// Optional parameters and default parameters
function greet(name: string, greeting: string = "Hello"): void {
console.log(`${greeting}, ${name}!`);
}
// Rest parameters
function sum(...numbers: number[]): number {
return numbers.reduce((acc, curr) => acc + curr, 0);
}
Generics
Generics allow defining functions, interfaces, or classes without specifying the exact type upfront, deferring it until usage.
// Generic function
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("hello");
let output2 = identity<number>(42);
// Generic interface
interface GenericArray<T> {
[index: number]: T;
}
let myArray: GenericArray<number> = [1, 2, 3];
// Generic class
class GenericBox<T> {
private value: T;
constructor(value: T) {
this.value = value;
}
getValue(): T {
return this.value;
}
}
let box = new GenericBox<string>("secret");
console.log(box.getValue()); // Output: "secret"
Advanced Types
TypeScript provides advanced type utilities for handling more complex type scenarios.
// Mapped types
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
interface Person {
name: string;
age: number;
}
type ReadonlyPerson = Readonly<Person>;
// ReadonlyPerson is equivalent to:
// {
// readonly name: string;
// readonly age: number;
// }
// Conditional types
type IsString<T> = T extends string ? true : false;
type A = IsString<"hello">; // true
type B = IsString<123>; // false
// Index access types
type PersonName = Person["name"]; // string
type PersonKeys = keyof Person; // "name" | "age"
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:开发环境搭建与工具链
下一篇:TypeScript核心知识点