[TOC] <br/><br/><br/> # <b style="color:#4F4F4F;">简介说明</b> 原文链接: - [TypeScript](https://www.typescriptlang.org/) - [github](https://github.com/microsoft/TypeScript) - [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped) - [Triple-Slash Directives(三重斜杠指令)](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html) - [Typescript 书写声明文件](https://juejin.cn/post/6844904034621456398) - [TypeScript Compiler API 使用简介](https://meixg.cn/2020/06/24/typescript-compiler-api/) - [使用 TypeScript complier API](https://zhuanlan.zhihu.com/p/141410800) ``` 版本:TypeScript 作用:JavaScript的一个超集,而且本质上向这个语言添加了可选的静态类型和基于类的面向对象编程 ``` <br/> # <b style="color:#4F4F4F;">基本语法</b> <br/> # <span style="color:#619BE4">&</span> ***** 联合类型,将两个类型合并 <br/> # <span style="color:#619BE4">-</span> ***** 删除已定义操作符 <br/> # <span style="color:#619BE4">+</span> ***** 添加已定义操作符 <br/> # <span style="color:#619BE4">?:</span> ***** 声明该内容是可选的,不代表可以定义为null <br/> # <span style="color:#619BE4">[]</span> ***** 任意参数接口 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` // 当string类型和number都存在时,number值必须是string值子类型 interface Point { [key: string]: string, [key: number]: string, } ``` <br/> # <span style="color:#619BE4">abstract</span> ***** 声明抽象类和抽象方法 <br/> # <span style="color:#619BE4">as</span> ***** 类型断言 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` let el; // 类似类型转换,断言变量是某种类型 (<HTMLImageElement>el).src; // 第二种写法 (el as HTMLImageElement).src; ``` <br/> # <span style="color:#619BE4">declare</span> ***** 编写描述文件时,定义声明内容关键字 <br/> # <span style="color:#619BE4">decorator</span> ***** 装饰器函数,在TS中装饰器只能作用于类 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` 修饰方法时: function log(target: any, name: any, descriptor: PropertyDescriptor) { let fn = descriptor.value; descriptor.value = function (x: number, y: number): number { console.log(x); console.log(y); let result = fn(x, y); result += 128; return result; } } class Method { @log add(x: number, y: number): number { return x + y } } let m = new Method(); console.log(m.add(1, 2)); ``` <span style="color:red;">2. React HOC使用</span> ``` const Hoc = (Com: ComponentClass<any>) => { return class Go extends Com{ render() { return <div> hello <Com/> world </div>; } } }; @Hoc class TList extends Component<any, any> { render(){ return <div>你好哇</div> } } ``` <br/> # <span style="color:#619BE4">enum</span> ***** 定义枚举类型 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` enum HTTP_CODE { OK = 200, ERROR = 400, NOT_FOUND = 404 } ``` <br/> # <span style="color:#619BE4">extends</span> ***** 类型继承,用于泛型时可以约束泛型格式 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` 将T中可以继承U的内容选出返回never T extends U ? never : T; ``` <span style="color:red;">2. 查找类型 + 泛型 + keyof</span> ``` interface API { '/user': { name: string }, '/menu': { foods: string[] } } const get = <URL extends keyof API>(url: URL): Promise<API[URL]> => { return fetch(url).then(res => res.json()); } get(''); get('/menu').then(user => user.foods); ``` <br/> # <span style="color:#619BE4">infer</span> ***** 表示在 extends 条件语句中待推断的类型变量 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` type ParamType<T> = T extends (param: infer P) => any ? P : T; 在这个条件语句 T extends (param: infer P) => any ? P : T 中,infer P 表示待推断的函数参数。 整句表示为:如果 T 能赋值给 (param: infer P) => any,则结果是 (param: infer P) => any 类型 中的参数 P,否则返回为 T。 ``` <br/> # <span style="color:#619BE4">get | set</span> ***** 访问寄存器关键字 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` class Person { constructor() { } private _name: string; public get name() { return this._name; } public set name(name: string) { this._name = name; } } ``` <br/> # <span style="color:#619BE4">in</span> ***** 遍历类型集体声明类型,type专属 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` interface IPerson { name: string, age: number } type IDummyPerson = { [k in keyof IPerson]: string } let obj: IDummyPerson = { name: "", age: "" }; function getVal(k: keyof typeof obj) { return obj[k]; } getVal("name"); ``` <br/> # <span style="color:#619BE4">type</span> ***** 声明类型变量,可以作用于原始值(基本类型),联合类型,元组以及其它任何你需要手写的类型 <br/> ### 示例内容 <span style="color:red;">1. 拓展类型</span> ``` type PartialPointX = { x: number; }; type Point = PartialPointX & { y: number; }; ``` <br/> # <span style="color:#619BE4">interface</span> ***** 定义接口 <br/> ### 示例内容 <span style="color:red;">1. 定义函数</span> ``` interface IFunc { (x: number, y: number): number } interface IObj { fn: (x: number, y: number) => number, fn2(x: number, y: number): number, } ``` <span style="color:red;">2. 定义数组</span> ``` let arr: number[] = [1, 2, 3, 4] // 数字数组 不允许出现其他数据类型 let arr2: string[] = ['h', 'h', 'h'] // 字符串数组 let arr3: any[] = [1, 'h', 'h', 3] //允许数组中出现任意类型 interface arr {[index: number]: number} let list: arr = [1, 2, 3, 4] let arr: Array<string> = ['bonjour', 'hello'] let arr2: Array<number> = [1, 2] let arr3: Array<any> = [1, 2, 'hh'] ``` <span style="color:red;">3. 定义键值为symbol</span> ``` const a:unique symbol=Symbol(); interface eventPool { [a]: number, } ``` <span style="color:red;">4. 只读属性</span> ``` interface Point { readonly x: number; } interface Preson { name: string; age?: number; [propName: string]: any } ``` <span style="color:red;">5. 类型拓展</span> ``` Interface extends interface interface PartialPointX { x: number; } interface Point extends PartialPointX { y: number; } Type alias extends type alias type PartialPointX = { x: number; }; type Point = PartialPointX & { y: number; }; Interface extends type alias type PartialPointX = { x: number; }; interface Point extends PartialPointX { y: number; } Type alias extends interface interface PartialPointX { x: number; } type Point = PartialPointX & { y: number; }; ``` <span style="color:red;">6. 常用类型定义</span> ``` // 定义函数的参数可以不全部接收 interface func { (): string } interface obj { a: string b: (x: number, y: number) => number } interface cla { new(): cla } ``` <span style="color:red;">7. 定义</span> ``` export interface ThunkDispatch<S, E, A extends Action> { <T extends A>(action: T): T; <R>(asyncAction: ThunkAction<R, S, E, A>): R; } export type ThunkAction<R, S, E, A extends Action> = ( dispatch: ThunkDispatch<S, E, A>, getState: () => S, extraArgument: E ) => R; ``` <span style="color:red;">8. 函数泛型</span> ``` export interface ThunkDispatch { <R>(x: R): R; } function f(dispatch: ThunkDispatch) { let a = dispatch<{ x: number }>({x: 1}); a.x } 箭头函数hack const foo = <T extends {}>(x: T) => x; ``` <span style="color:red;">9. 模板字符串类型前缀</span> ``` type addPrefix<TKey, TPrefix extends string> = TKey extends string ? `${TPrefix}${TKey}` : never; type removePrefix<TPrefixedKey, TPrefix extends string> = TPrefixedKey extends addPrefix<infer TKey, TPrefix> ? TKey : ''; type prefixedValue<TObject extends object, TPrefixedKey extends string, TPrefix extends string> = TObject extends {[K in removePrefix<TPrefixedKey, TPrefix>]: infer TValue} ? TValue : never; type addPrefixToObject<TObject extends object, TPrefix extends string> = { [K in addPrefix<keyof TObject, TPrefix>]: prefixedValue<TObject, K, TPrefix> } ``` <br/> # <span style="color:#619BE4">is</span> ***** 自定义类型保护 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` function canEach(data: any): data is Element[] | NodeList { return data.forEach !== undefined; } function f(elements: Element[] | NodeList | Element) { if (canEach(elements)) { console.log(elements.forEach) } } ``` <br/> # <span style="color:#619BE4">keyof</span> ***** 索引类型查询操作符 <br/> # <span style="color:#619BE4">typeof</span> ***** 获取对象type类型 <br/> ### 示例内容 <span style="color:red;">1. 数组内容转key集合</span> ``` typeof keys[number] ``` <br/> # <span style="color:#619BE4">namespace</span> ***** 命名空间,在模块内部划分模块,同名命名空间会合并 <br/> # <span style="color:#619BE4">new</span> ***** 类型与类类型 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` class Obj { name: string; age: number; constructor(name: string, age: number) { this.name = name; this.age = age; } } interface IObjConstructor { new(name: string, age: number): void } interface IObjClass { name: string; age: number; } function ObjConstructor(Obj: IObjConstructor) { let o = new Obj("", 0); console.log(o); } function ObjClass(o: IObjClass) { console.log(o); } ObjConstructor(Obj); ObjClass(new Obj("", 0)); ``` <br/> # <span style="color:#619BE4">this</span> ***** 描述this对象 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` interface IObj { name: string, fn(): number } let obj: IObj = { name: "SystemLight", fn(this: IObj): number { console.log(this.name); return 1; } }; ``` <span style="color:red;">2. 原型链实现</span> ``` interface IBus { } const Bus = function (this: IBus) { const [state, setState] = useState(false); console.log(state); } as any as { new(): IBus; } ``` <br/> # <span style="color:#619BE4">unknow</span> ***** 安全版本的any,只能赋值给any或者unknown,没有任何属性和方法 <br/> # <span style="color:#619BE4">never</span> ***** 声明函数永远不会返回,如函数抛出错误,也可以说是一个无效类型 <br/> ### 示例内容 <span style="color:red;">1. 举例说明</span> ``` export function a(x: ExpandTouchEvent<{}>): never { throw Error(); } ``` <br/>