静态类型系统概述
静态类型系统在编程语言中扮演着重要角色,它通过编译时类型检查帮助开发者捕获潜在错误,提升代码可维护性。TypeScript作为JavaScript的超集,其类型系统既强大又灵活,支持从基础类型到复杂泛型的多种特性。
静态类型与动态类型的区别
静态类型系统在编译阶段进行类型检查,而动态类型系统在运行时才确定类型。例如:
// TypeScript(静态类型)
let age: number = 25;
age = "thirty"; // 编译时报错
// JavaScript(动态类型)
let age = 25;
age = "thirty"; // 运行时不会报错
静态类型的优势在于:
- 早期错误检测
- 更好的IDE支持
- 代码可读性提升
- 重构安全性
TypeScript基础类型
TypeScript提供了与JavaScript相同的基础类型,但增加了类型注解:
let isDone: boolean = false;
let decimal: number = 6;
let color: string = "blue";
let list: number[] = [1, 2, 3];
let tuple: [string, number] = ["hello", 10]; // 元组类型
特殊类型包括:
any
: 禁用类型检查void
: 表示没有返回值never
: 表示永不返回的函数unknown
: 类型安全的any
接口与类型别名
接口(interface)和类型别名(type)是定义复杂类型的两种主要方式:
// 接口
interface User {
name: string;
age?: number; // 可选属性
readonly id: number; // 只读属性
}
// 类型别名
type Point = {
x: number;
y: number;
};
// 扩展接口
interface Admin extends User {
permissions: string[];
}
// 扩展类型
type AdminUser = User & { permissions: string[] };
关键区别:
- 接口支持声明合并
- 类型别名可以使用联合类型和元组
泛型编程
泛型允许创建可重用的组件:
function identity<T>(arg: T): T {
return arg;
}
let output = identity<string>("myString");
// 泛型接口
interface GenericIdentityFn<T> {
(arg: T): T;
}
// 泛型类
class GenericNumber<T> {
zeroValue: T;
add: (x: T, y: T) => T;
}
约束泛型:
interface Lengthwise {
length: number;
}
function loggingIdentity<T extends Lengthwise>(arg: T): T {
console.log(arg.length);
return arg;
}
高级类型
TypeScript提供了丰富的高级类型特性:
联合类型与交叉类型
type StringOrNumber = string | number;
type Admin = User & { permissions: string[] };
类型守卫
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
}
映射类型
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
type Partial<T> = {
[P in keyof T]?: T[P];
};
条件类型
type NonNullable<T> = T extends null | undefined ? never : T;
类型推断与类型断言
TypeScript具有强大的类型推断能力:
let x = 3; // 推断为number类型
类型断言:
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
模块与命名空间
TypeScript支持ES模块和命名空间:
// 模块
import { Module } from "./module";
export const pi = 3.14;
// 命名空间
namespace Validation {
export interface StringValidator {
isAcceptable(s: string): boolean;
}
}
装饰器
装饰器是一种特殊声明:
function sealed(constructor: Function) {
Object.seal(constructor);
Object.seal(constructor.prototype);
}
@sealed
class BugReport {
type = "report";
title: string;
constructor(t: string) {
this.title = t;
}
}
实用工具类型
TypeScript内置了多个实用工具类型:
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Pick<Todo, "title" | "completed">;
type TodoOmit = Omit<Todo, "description">;
type TodoPartial = Partial<Todo>;
type TodoRequired = Required<Todo>;
类型声明文件
TypeScript使用.d.ts
文件来描述JavaScript库的类型:
// jquery.d.ts
declare namespace JQuery {
interface AjaxSettings {
method?: "GET" | "POST";
data?: any;
}
function ajax(url: string, settings?: AjaxSettings): void;
}
最新类型特性
TypeScript持续演进,新增特性包括:
- 模板字面量类型
type World = "world";
type Greeting = `hello ${World}`;
- 可变元组类型
type Strings = [string, string];
type Numbers = [number, number];
type StrNum = [...Strings, ...Numbers]; // [string, string, number, number]
- 递归类型别名
type Json = string | number | boolean | null | Json[] | { [key: string]: Json };
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
下一篇:类型注解与类型推断