初见Typescript
Why?
-
静态类型检查(非运行时检查)
- IDE智能提示(推荐VsCode)
- 可读性,可维护性
- 构建大型项目的能力
- 提前发现错误
- 接口化,抽象化,根据接口自动生成文档

类型
export interface StorageModule {
getItem: (key: string) => any,
setItem: (key: string, value: string | boolean | number, isConst?: boolean) => void,
removeItem: (key: string) => void,
hasItem: (key: string) => boolean,
keys: () => any[],
datas: StorageData
}
interface StorageData {
[index: string]: any
}

接口
对值所具有的结构进行类型检查
函数重载
非传统意义的函数重载
泛型
在成员之间提供有意义的类型约束,并提高复用性
成员可以是
- 类的方法
- 类的实例成员
- 函数参数
- 函数返回值
- 等
- 使用kiwi-cli 创建项目
- 安装TS相关 (ts-loader, typescript, tslint, tslint-loader, tslint-cong-standard)
- 配置webpack
- 添加tsconfig.json (被ts-loader解析,类似于.babelrc)
- 增加eslint-plugin-vue (为vue增加代码规范审查)
-
检查版本,查看vue全家桶是否有@type文件
kiwi-cli 使用的是cdn引入的vue,vue-router vux,
需重新安装,并配置排除外部依赖
由kiwi-cli过渡
tsconfig.json
第三方库引入问题 (1. 具有声明文件的库 2. 无声明文件例ACE )

XXX.d.ts
declare module '@napos/melody-os'
declare module '@napos/ace/plugins/vue'
与js的‘桥梁’
不需要引入,TS会查找目录下 .d.ts文件
文件内不允许除声明以外的操作
某些值没有索引类型错误信息 (1.添加索引类型 2. 类型断言)


./src/compontent/index.ts
由于eslint不识别Ts的写法(@g),所以我们在.eslintrc 弃用babel-eslint 使用 typescript-eslint-parser
eslint对Vue文件报错

https://github.com/vuejs/eslint-plugin-vue
https://github.com/eslint/typescript-eslint-parser
untils
export { default as converter } from './converter'
// 放弃 下面的写法
// import converter from './converter'
// export {
// converter
// }
@/为什么不生效
类型“VueConstructor<Vue>”上不存在属性“$shop”
解决:模块补充 ./types/XX.d.ts
import Vue from 'vue'
declare module 'vue/types/vue' {
interface Vue {
$url: string
}
interface VueConstructor {
$shop: any
}
}
// 可以通过 let vm = new Vue() vm.$url 将不会报错
在具有类型推断的情况下,我们要把类型检查做到什么程度,换而言之,我们在类型推断正确的情况下,是否还要自己写接口,进而限定它的类型?

Class Person {}
// 编译为
------
function _classCallCheck(instance, Constructor) {
// 检查是否成功创建了一个对象
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function")
}
}
var Person = function Person() {
_classCallCheck(this, Person);
}
--------
let person = new Person() // 正常
Person()
// Uncaught TypeError: Cannot call a class as a function
------
// import Ace from '@napos/ace'
import Ace from '@napos/ace/plugins/vue'
Vue.use(Ace, config)
最后经排查,是kiwi-cli 引入Ace方式问题
装饰器
组件
vuex
编译时发现错误
or
运行时发现错误
若人生只如初见~你会选择
Typescript 指北
By xuhao
Typescript 指北
- 288