Why TS
popular TS vs. JS
- ts is more than js
- Support for static and dynamic types
- Errors can be found and corrected during Compilation
- change of data type is forbidden
What can we get when using TS: datatype safety, new js feature, complete tool chain.
Recommend Resources: AwesomeTS, playground essential
ts Basic
Data Type
- boolean ,number ,string
- enum
- any ,unknown , void
- never 不存在值,防御
- Arr[]数组
- tuple 元组
函数重载,多次定义,前几次是定义,最后一次是实现
function add(x:number[]):number
function add(x:string[]):string
function add(x:any[]):any{
if(typeof x[0]==='string'){
return x.json()
}
if(typeof x[0]==='number'){
return x.reduce((acc,cur)=> acc + cur)
}
}
Interface,接口 Def: to define object types Feature:
- optional properties: ?
- readOnly:
- describe Function type
- describe custom properties
Class
- public
- private
- protected
ts Advanced
-
联合类型 | Union Types
let tag:Type1|Type2|Type3 -
交叉类型 &
-
类型断言
-
类型别名
泛型
基本定义:/Basic Def
- syntax
function print<T>(arg:T){
....
}
-
There are two ways to specify the type of use.
- Define the type to be used
- Automatically deduce the type by typescript type inference
-
temperary occupancy
Basic Operators
- typeof
- keyof
- in
- T[K]
- extends
Tool types
Partical<T>可选Required<T>必选Readonly<T>只读
TS in practice
声明文件/不确定要怎么翻译,查了再改
- declare
- .d.ts
- @types
- tsconfig.json
Q&A
- Why sometimes Ts to AnyScript
这是很常见的情况
- 存量项目改造:改造成本,逐渐完善
- 新建项目:建议定义类型