创建项目

  1. npx create-react-app 项目名 --template typescript

项目目录结构

  1. // 根目录
  2. // 新增tsconfig.json文件 ts的配置文件 指定ts在编译时的选项
  3. // src目录
  4. // 组件的扩展名变为tsx
  5. // 新增react-app-env.d.ts 项目默认的类型声明文件
  6. // 使用三斜线指令指定依赖的其他类型声明文件 types 表示依赖的类型声明文件包的名称
  7. /// <reference types='react-acripts'>
  8. // react-acripts 包 提供类型声明
  9. // react react-dom node 的类型
  10. // 图片 样式 等其他模块的类型 允许在代码中导入图片 svg等文件

tsconfig.json

项目文件和编译所需要的配置项
使用 tsc—init 可以自动生成该文件

  1. {
  2. // 编译配置
  3. "compilerOptions": {
  4. // 编译为js的版本
  5. "target": "es5",
  6. // 指定要包含在编译中的 libary (库)
  7. "lib": [
  8. "dom",
  9. "dom.iterable",
  10. "esnext"
  11. ],
  12. // 允许ts编译为js 文件
  13. "allowJs": true,
  14. // 跳过声明文件的类型检查
  15. "skipLibCheck": true,
  16. // 屏蔽 ES6 CommonJs 间的差异
  17. "esModuleInterop": true,
  18. // 允许 使用 import X from 'y' 进行导入 模块没有default也是可以的
  19. "allowSyntheticDefaultImports": true,
  20. // 开启严格模式
  21. "strict": true,
  22. // 文件名强制区分大小写
  23. "forceConsistentCasingInFileNames": true,
  24. // switch 语句启用错误报告
  25. "noFallthroughCasesInSwitch": true,
  26. // 指定生成代码的模块化标准
  27. "module": "esnext",
  28. // 模块解析策略
  29. "moduleResolution": "node",
  30. // 允许导入扩展名为json的文件
  31. "resolveJsonModule": true,
  32. // 是否将 没有 import/export 的文件作为全局非模块化的脚本文件
  33. "isolatedModules": true,
  34. // 编译时不生成任何文件 使用babel进行处理
  35. "noEmit": true,
  36. // 指定jsx编译为的语法
  37. "jsx": "react-jsx"
  38. },
  39. // 指定项目中允许ts 处理的目录 自动装载其中的 .d.ts文件
  40. "include": [
  41. "src"
  42. ]
  43. }

react中常用类型

  1. // 函数组件
  2. // FC 函数组件的类型 也可以不写FC 使用TS的类型推论
  3. // 属性的默认值
  4. 函数名.defaultProps = {
  5. 属性名:值
  6. }
  7. 或者直接使用ES6 的默认值