定义
TypeScript 是一种由微软开发的开源编程语言,它是 JavaScript 的超集,添加了可选的静态类型系统和一些现代语言特性
常用技巧
-
类型注解
针对目标:为变量、函数参数和返回值指定类型
let count: number = 42; // 变量类型注解
function add(a: number, b: number): number { // 函数参数和返回值类型注解
return a + b;
}
-
接口
针对目标:定义对象的形状(结构),确保对象具有特定的属性和方法。
interface User {
id: number;
name: string;
email: string;
}
const user: User = {
id: 1,
name: "Alice",
email: "alice@example.com"
};
-
类
可用于继承,访问修饰符 4. ## 泛型 针对目标:可重用组件,适用多种类型
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("Hello"); // 类型为 string
let output2 = identity<number>(42); // 类型为 number
高级类型
交叉类型 T & U
表示一个值必须同时满足多种类型。
function extend<T , U>(first: T, second: U) : T & U {
let result: <T & U> = {}
for (let key in first) {
result[key] = first[key]
}
for (let key in second) {
if(!result.hasOwnProperty(key)) {
result[key] = second[key]
}
}
return result
}
联合类型 T | U
表示一个值可以是多种类型之一。
function formatCommandline(command: string[] | string) {
let line = '';
if (typeof command === 'string') {
line = command.trim();
} else {
line = command.join(' ').trim();
}
}
类型别名
为复杂定一个名称
type StringOrNumber = string | number;
let value: StringOrNumber;
value = "Hello";
value = 42;
类型断言
手动指定一个值的类型
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
装饰器(Decorators)
附加到类、方法、属性或参数上,用于修改或扩展其行为
类型索引 keyof
interface Button {
type: string
text: string
}
type ButtonKeys = keyof Button
//等效于
type ButtonKeys = "type" | "text"
类型约束 extend
type BaseType = string | number | boolean
//copy的参数只能是字符串、数字和布尔
function copy<T extends BaseType>(arg: T): T {
return arg
}
工具类型
可选:Partial 只读:Readonly 选择:Pick 排除:Omit
interface User {
id: number;
name: string;
email: string;
}
// Partial: 将所有属性变为可选
type PartialUser = Partial<User>;
// Readonly: 将所有属性变为只读
type ReadonlyUser = Readonly<User>;
// Pick: 选择部分属性
type UserNameAndEmail = Pick<User, "name" | "email">;
// Omit: 排除部分属性
type UserWithoutEmail = Omit<User, "email">;
拓展
as和!区别
AS是断言类型, !表示非空断言
type和interface区别
- 扩展性
-
interface:可以通过
extends
扩展其他接口。interface A { name: string; } interface B extends A { age: number; }
-
type:可以通过交叉类型(
&
)扩展其他类型。type A = { name: string; }; type B = A & { age: number; };
- 合并声明
-
interface:支持声明合并,同名的接口会自动合并。
interface A { name: string; } interface A { age: number; } const obj: A = { name: 'John', age: 30, };
-
type:不支持声明合并,同名类型会报错。
- 实现类
-
interface:可以被类实现(
implements
)。interface A { name: string; } class B implements A { name: string; }
-
type:不能直接被类实现,但可以通过对象类型实现类似功能。
type A = { name: string; }; class B implements A { // Error: A class can only implement an object type. name: string; }
- 使用场景
- interface:更适合定义对象类型,尤其是需要扩展或实现时。
- type:更灵活,可以定义联合类型、交叉类型、元组等复杂类型。