这是我参与「第五届青训营 」伴学笔记创作活动的第 11 天
Typescript
Typescript作为javascript的超集,支持所有javascript的语法,可以通过编译器转译javascript,因此可以在任何支持javascript的环境运行。
Typescript为javascript提供了静态类型检查,形如:let aNum: number = 0。值得注意的是,typescript与c++等古老静态类型语言不同,不需要繁琐地进行显式类型申明,而是可以进行自动类型推断。
Typescript的类型是structure based type。即,只要类型的结构一致就会被认为是同一个类型。
Typescript类型基础
基础类型申明直接跳过
函数类型
function getFavoriteNumber(age: number): number {
return age;
}
: number定义了函数的返回值。
(age: number) => number直接定义函数的类型
对象类型
let obj: { first: string; last?: string } = {first: "gagua"}
?表示此属性可能不存在
obj.last: string | undefined
复用类型: Type Aliases or Interface
Type Alias可以用于定义一个类型别名。
type Point = {
x: number;
y: number;
};
等同于:
interface Point {
x: number;
y: number;
};
两者在于类型的继承方式上有微小的区别,Type Alias通过&符拓展对象,而interface通过extends关键字拓展对象。
对象字面量与字面量推断
const req = { url: "https://example.com", method: "GET" } as const;
handleRequest(req.url, req.method);
通过将对象设置为只读,避免了对对象method属性的更改,因此req.method的类型收敛为"GET"
常见高阶用法
infer 推断
type ReturnType<T> = T extends (...args: any[]) => infer P ? P : any;
表示如果T属于(...args: any[]) => P这一函数的类型,则通过infer关键字推断,将函数的返回值的类型P作为ReturnType<T>的类型,否则则为any类型。
函数泛型
function map<Input, Output>(arr: Input[], func: (arg: Input) => Output): Output[] {
return arr.map(func);
}
// Parameter 'n' is of type 'string'
// 'parsed' is of type 'number[]'
const parsed = map(["1", "2", "3"], (n) => parseInt(n));
可以从函数被调用时的输入来推断输出。
工具类型
虽然typescript提供了强大的类型编程工具。为了便于使用,typescript内置了部分工具类型。
type Partial<T> = {[P in keyof T]?: t[P] | undefined}
type Record<K extends string | number| symbol, T> = {[P in K]: T;}
等等
总结
typescript引入静态类型解决了javascript在大型软件开发中常常遇到的类型错误,将一部分运行时错误提前到了编译时检查。兼容javascript语法便于利用javascript生态,俨然已经成为了javascript生态中不可或缺的一部分。