考虑到现在项目中主要使用 JS ,以及 TS 的学习成本,采用渐进式迁移的方案,允许使用 JS 或 TS 编写组件代码,对使用 TS 编写的组件进行编译。
如果是自己搭建的项目,可以参考以下方案:
Webpack 转译 Typescript 现有方案
有了 @babel/preset-typescript ,配置 TypeScript 环境确实方便了很多。需要注意的是,@babel/preset-typescript 只做语法转换,不做类型检查,因为类型检查的任务可以交给 IDE (或者用 tsc)去做。
另外,Babel 负责两件事:1)语法转换,由各种 transform 插件、helpers 完成;2)对于可 polyfill 的 API 的提供,由 corejs 实现。@babel/plugin-transform-runtime 插件可用于减少生成代码的量,以及对 corejs 提供的 API 与 runtime 提供的帮助函数(helpers)进行模块隔离。
Babel 7 下配置 TypeScript 支持
@babel/preset-typescript - 印记中文
如果是脚手架搭建的项目,直接安装依赖:
$ npm install --save typescript @types/node @types/react @types/react-dom @types/jest
Type 和 Interface
函数两种声明方式
interface Props {
setCount: (val: boolean) => void;
function setVisible(val: boolean): void;
}
数组的声明
在 JS 中,array 代表一种类型,但是 TS 里面声明数组的类型不能用 array ,可以使用下面的方法:
const arr: string[] = [];
如果要给数组添加多个类型,可以使用下面的方法:
const arr: (string | number)[] = [];
此外也可以使用 Array 和 Iterable 接口:
const arr: Array<string | number> = [];
const arr: Iterable<string | number> = [];
自己实现一个泛型接口
实现数组泛型接口:
type MyArray<T> = T[];
const arr: MyArray<string> = [];
实现 Map 对象的泛型接口:
type MyMap<K, V> = Map<K, V>;
const map: MyMap<string, string[]> = new Map();
模块的声明
在 TS 中使用 JS 模块,import 声明会出现下滑线,提示找不到 TS 声明文件。这个时候需要在 JS 文件同级目录下添加 xx.d.ts 声明文件:
declare module '@rematch/core' {
export function init<M extends Models>(config: any): any;
}
TS 类型声明文件无需导出,TS 会自动在同级目录下找 xxx.d.ts 声明文件
声明可选字段
type Props = {
name: string;
enthusiasmLevel?: number;
}
声明两种类型
TS 的变量可以声明两种数据类型
type Props = {
name: string;
age: string | null;
}
导出类型接口
导出类型接口,以便在组件中使用
export interface Person {
name: string;
age: number;
sex: number | boolean;
hobby?: string[];
}
很多 npm 包都会对外暴露类型接口,这样无需自己添加类型声明了
参考
typescript-react-starter 用ts类型系统实现斐波那契数列
|