环境
类型
TS中的类型
类型 |
例子 |
描述 |
number |
1, 2, 3.5 |
任意数字 |
string |
“hi” |
字符串 |
boolean |
true、false |
布尔值 |
字面量 |
字面量本身 |
|
any |
/ |
任意类型 |
unknow |
/ |
类型安全的 any |
void |
空值 (undefined) |
|
never |
没有值 |
不能是任何值 (可用于抛出异常的函数) |
object |
{a: “a”} |
任意 js 对象 |
array |
[1, 2, 3] |
任意 js 数组 |
tuple |
[123, 456] |
元组(固定长度的数字) |
enum |
xx.xx |
枚举 |
联合类型
类型断言
1 2 3 4 5
| type str = string; let a: unknown let b: str b = a as str b = <str>a
|
数组类型的定义
1 2
| let a: number[] let a: Array<number>
|
接口
1 2 3 4 5 6 7 8 9 10 11 12
| interface Test { readonly id: number name: string; age?: string; [propName: string]: string ; }
let t: Test = { id: 666, name: 'YuanZhang', gender: 'male' }
|
抽象类
1 2 3 4 5 6 7 8 9 10 11 12
| abstract class Animal { abstract makeSound(): void; move(): void { console.log('moving...'); } }
class Dog extends Animal { makeSound() { console.log('woof! woof!'); } }
|
封装
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Test{ public name: string; private _id: number; constructor(name: string, id: number){ this.name = name; this._id = id; } get id(){ return this._id; } set id(id: number){ this._id = id; } }
|
泛型
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| function fn<T, K>(a: T, b:K) { return a; } fn(1, "HELLO"); fn<string, string>('1', "HELLO");
interface In{ length: number; }
function fn2<T extends In>(a){ return a.length; }
|
tsconfig.json
tsconfig.json (tslang.cn)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| { "compilerOptions": { "module": "ES6", "target": "ES6", "sourceMap": true, "outDir": "./dist", "removeComments": true, "noEmitOnError": true, "alwaysStrict": true,
}, "include": [ "src/**/*" ]
}
|