typescript 使用
ts常用命令:
yarn init --yes 默认初始化项目
yarn add typescript --dev 本地安装ts
yarn tsc xxx 编译文件 (检查语法错误,去除注释,转化为es5)
yarn tsc --init tsconfig.json文件配置
yarn tsc --locale zh-CN 中文显示错误消息
tsconfig.json文件配置
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "dist", /* Redirect output structure to the directory. */
"rootDir": "src",
标准库:内置对象所对应的声明
如果配置文件中target设置为es5, 则在ts文件中使用es6新增的promise等会报错,因为没有对应的标准库文件引入,解决方式:配置对应的标准库
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["ES2015", "DOM"],
数组类型:
const arr1: Array<number> = [1, 2, 3]
//等价写法
const arr2: number[] = [1, 2, 3]
元组类型:明确元素数量与类型
常用于函数返回值
类型断言: as ; 类型编译过程
接口interface:约定成员及成员类型
interface Post {
subtitle?: string //可选成员
readonly summary: string //只读
}
- 动态成员
interface Cache {
[prop: string]: string
}
const cache: Cache = { }
cache.foo = 'value1';
cache.bar = "value2";
泛型 :< T >
在使用时确认类型,先用T代替