安装 typescript
c
cnpm install --save-dev typescript @types/react @types/react-dom
- typescript 包是 TS 的核心编译器,提供类型检查、类型推导、代码补全等功能。
- @types/react 包是 react 的类型声明文件
- @types/react-dom 包是 react-dom 的类型声明文件
生成 typescript 配置文件 tsconfig.json
c
npx tsc --init
在默认生成配置基础上,添加已定义的配置,最终效果为
c
{
"compilerOptions": {
// 跟随 TS 更新持续适配最新 Node 特性
"module": "nodenext",
// 支持最新版的ES语法
"target": "esnext",
// 不自动引入任何类型定义
"types": [],
// 使用到的API
"lib": ["esnext", "DOM", "DOM.Iterable"],
// 生成source map文件便于调试
"sourceMap": true,
// 生成声明文件(.d.ts)
"declaration": true,
// 为声明文件生成source map
"declarationMap": true,
// 索引访问需要进行非空检查
"noUncheckedIndexedAccess": true,
// 严格的可选属性类型检查
"exactOptionalPropertyTypes": true,
// 开启所有严格类型检查选项
"strict": true,
// 强制使用import type语法导入类型
"verbatimModuleSyntax": true,
// 确保每个文件都能作为独立模块进行编译
"isolatedModules": true,
// 禁止导入有未检查副作用的模块
"noUncheckedSideEffectImports": true,
// 强制检测模块系统
"moduleDetection": "force",
// 跳过对第三方包的类型检查
"skipLibCheck": true,
// 支持旧版commonJS包的引入
"esModuleInterop": true,
// 允许TS中写js
"allowJs": true,
// 支持省略 import react from "react"
"jsx": "react-jsx",
// 强制文件名大小写一致,避免跨平台问题
"forceConsistentCasingInFileNames": true,
// 不生成JS文件(vite生成,无需ts处理)
"noEmit": true
}
}
改文件后缀 .jsx 为 .tsx
解决TS类型校验产生的红色波浪线报错
确定有值的
末尾加 !
c
document.getElementById("root")!
缺类型文件的
新增类型文件,如 src/index.d.ts
c
declare module "*.css" {
const content: string;
export default content;
}
declare module "*.module.css" {
const classes: { [key: string]: string };
export default classes;
}
declare module "*.svg" {
const content: string;
export default content;
}
declare module "*.png" {
const content: string;
export default content;
}
declare module "*.jpg" {
const content: string;
export default content;
}
declare module "*.jpeg" {
const content: string;
export default content;
}
缺类型声明的
添加类型声明
react 的通用元素类型 -- ReactNode
c
import type { ReactNode } from "react";
interface MainLayoutProps {
header?: ReactNode;
content?: ReactNode;
footer?: ReactNode;
}
const MainLayout = ({ header, content, footer }: MainLayoutProps) => {
return (
<div>
{header ?? <h1>默认标题</h1>}
{content ?? <p>默认内容</p>}
{footer ?? <p>默认页脚</p>}
</div>
);
};
export default MainLayout;
ReactNode 是内置类型,具体定义如下
c
// @types/react 内置类型
type ReactNode =
| ReactElement
| string
| number
| null
| undefined
| boolean
| Iterable<ReactNode>
| ReactPortal;
- ReactElement 即 JSX 元素
- Iterable
<ReactNode>指数组 \[\]、Set 等可迭代对象 - ReactPortal 为 React.createPortal(children, dom) 传送门
react 事件类型
html
<div onClick={handleClick}>
c
const handleClick = (e: React.MouseEvent<HTMLDivElement>) => {
console.log("点击了");
};