TypeScript是一种由微软开发的开源编程语言,它是JavaScript的一个超集,增加了类型系统和其他现代编程语言特性。TypeScript的类型系统是它最强大的特性之一,它可以帮助开发者编写更安全、更易于维护的代码。以下是从基础到高级的TypeScript类型系统实用指南。
基础类型
TypeScript提供了多种基础类型,包括:
布尔类型(Boolean)
let isDone: boolean = false;
数字类型(Number)
let age: number = 26;
字符串类型(String)
let name: string = "Alice";
字符类型(Character)
let char: string = 'A';
任意类型(Any)
let notSure: any = 4;
notSure = "maybe a string instead";
Void类型
当没有返回值时使用:
function sayHello(): void {
console.log("Hello, world!");
}
Null和Undefined类型
let u: undefined = undefined;
let n: null = null;
联合类型(Union Types)
联合类型表示变量可以是多种类型中的一种:
let age: number | string = 26;
age = "twenty six";
高级类型
接口(Interfaces)
接口定义了对象的形状:
interface Person {
name: string;
age: number;
}
let person: Person = {
name: "Alice",
age: 26
};
类(Classes)
类是对对象的抽象,包含属性和方法:
class Animal {
public name: string;
constructor(name: string) {
this.name = name;
}
makeSound() {
console.log("Some sound");
}
}
泛型(Generics)
泛型允许在多个地方重复使用相同的类型:
function getArray<T>(items: T[]): T[] {
return new Array<T>().concat(items);
}
let numArray = getArray<number>([1, 2, 3, 4]);
let strArray = getArray<string>(["Alice", "Bob"]);
枚举(Enums)
枚举是对一组数值的命名集合:
enum Color {
Red,
Green,
Blue
}
let c: Color = Color.Green;
高级类型运算符
- 类型别名(Type Aliases)
type Point = {
x: number;
y: number;
};
let p: Point = { x: 10, y: 20 };
- 映射类型(Mapped Types)
type mappedType<T> = {
[P in keyof T]: T[P];
};
let x: mappedType<{a: number; b: string}> = { a: 1, b: "test" };
- 条件类型(Conditional Types)
type T1 = "a" | "b";
type T2 = "c" | "d";
type Condition<T> = T extends "a" | "b" ? T : T extends "c" | "d" ? string : number;
let x: Condition<T1> = "a"; // string
let y: Condition<T2> = "c"; // string
let z: Condition<T2> = 10; // number
高级类型模式
- 模板字符串(Template Literals)
let personName = `Alice's age is ${person.age}`;
- 遍历对象键(Keyof Operator)
type Person = {
name: string;
age: number;
};
type PersonKeys = keyof Person; // "name" | "age"
- 可选链操作符(Optional Chaining Operator)
let person = {
name: "Alice",
age: 26,
address: {
street: "123 Main St",
city: "Wonderland"
}
};
console.log(person.address?.city); // "Wonderland"
实用技巧
- 使用类型推断(Type Inference)
TypeScript会根据代码自动推断类型,减少类型注解的使用:
let age = 26; // TypeScript推断age为number
- 避免重复的类型注解
使用类型别名和接口来避免重复的类型注解:
type Point = {
x: number;
y: number;
};
let p: Point = { x: 10, y: 20 };
- 使用类型守卫(Type Guards)
类型守卫可以帮助你确定一个变量是否具有某个特定的类型:
function isString(x: any): x is string {
return typeof x === "string";
}
function printId(id: any) {
if (isString(id)) {
console.log(id.toUpperCase());
} else {
console.log(id);
}
}
总结
掌握TypeScript的类型系统对于编写高质量、可维护的代码至关重要。从基础类型到高级类型,每个概念都有其独特的用途和优势。通过实践和深入理解,你可以利用TypeScript的类型系统来提高你的编码效率和代码质量。记住,TypeScript的类型系统是一个强大的工具,但使用它应该以增强代码可读性和减少错误为目标。
