05 — TypeScript 快速入门 30 分钟掌握 React 项目中用到的 TypeScript 语法。 TypeScript = JavaScript + 类型系统 。代码本身还是 JS,只是多了「类型标注」。
1. TypeScript 是什么? 1 2 3 4 5 6 7 8 9 10 11 function add (a, b ) { return a + b; } add ("5" , 3 ) function add (a : number , b : number ): number { return a + b; } add ("5" , 3 )
核心思想 :在写代码时(编译阶段)就能发现错误,IDE 还能智能提示。编译过程 :*.ts / *.tsx → tsc 编译 → *.js(浏览器只认识 JS)。
2. 项目里用到的所有 TS 语法(速查表) 下面是项目中实际出现的 TS 语法,挑你不会的看:
2.1 基础类型 1 2 3 4 5 6 7 8 9 10 11 12 let str : string = 'hello' ;let num : number = 42 ;let bool : boolean = true ;let nothing : null = null ;let notDefined : undefined = undefined ;let arr : number [] = [1 , 2 , 3 ];let arr2 : Array <string > = ['a' , 'b' ];let obj : { name : string ; age : number } = { name : 'Alice' , age : 30 };
2.2 联合类型(Union Type) 项目里到处都是 。
1 2 3 4 5 6 7 8 let value : string | null = null ; let flag : 'success' | 'error' = 'success' ; type Role = 'user' | 'assistant' ;type AgentId = 'chat' | 'file' | 'ppt' | 'deep' | 'skills' ;
项目例子 :
1 2 3 4 5 6 7 8 9 10 11 code : number ; message : string ;data : T; type AgentId = 'chat' | 'file' | 'ppt' | 'deep' | 'skills' ;role : 'user' | 'assistant' ;
2.3 数组类型 1 2 3 4 5 6 7 8 let list : string [] = ['a' , 'b' , 'c' ];let list2 : Array <string > = ['a' , 'b' , 'c' ]; chatList : Chat [];messages : ChatMessage [];agents : Agent [];timeline : TimelineItem [];
2.4 可选字段 ? 1 2 3 4 5 6 7 8 interface User { name : string ; age ?: number ; } const u1 : User = { name : 'A' }; const u2 : User = { name : 'B' , age : 30 }; const u3 : User = { age : 30 };
项目里 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 interface ChatMessage { id : string ; role : 'user' | 'assistant' ; content : string ; thinking ?: string []; timeline ?: TimelineItem []; reference ?: ReferenceItem []; recommend ?: string []; file ?: boolean ; fileName ?: string | null ; showTimeline ?: boolean ; copied ?: boolean ; pptFile ?: string ; timestamp : number ; }
读字段时要用 ?. 或 if 判断:
1 2 3 4 {message.timeline && message.timeline .length > 0 && ( <Timeline items ={message.timeline} open ={!!message.showTimeline} ... /> )}
2.5 接口 interface — 项目最常用 1 2 3 4 5 6 7 8 9 10 interface Props { chat : Chat ; active : boolean ; onSelect : (id : string ) => void ; onDelete ?: (id : string ) => void ; } function ChatItem ({ chat, active, onSelect, onDelete }: Props ) { ... }
2.6 type 别名 1 2 3 4 5 6 type AgentId = 'chat' | 'file' | 'ppt' | 'deep' | 'skills' ;type Callback = (id : string ) => void ;type Status = 'running' | 'completed' ;
什么时候用 interface,什么时候用 type?
场景 推荐 描述对象形状 interface联合类型 / 字面量 type函数类型 type(更简洁)需要扩展(extends) interface 或 type
项目里两种都用 。
2.7 泛型 <T> — 项目里有几个 1 2 3 4 5 6 7 8 function identity<T>(arg : T): T { return arg; } identity<string >('hello' ); identity (42 );
项目里的例子 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 async function parseOrThrow<T>(res : Response ): Promise <T> { ... return body.data as T; } async function httpGet<T>(path : string ): Promise <T> { ... } const data = await httpGet<{ records : SessionListVO [] }>('/session/list' );
2.8 函数类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 type OnSelect = (id : string ) => void ;interface Props { onSelect : (id : string ) => void ; } type AsyncFn = (id : string ) => Promise <void >;onSelect : (id : string ) => void ;onDelete ?: (id : string ) => void ;toggleTimeline : (id : string ) => void ;
2.9 类型断言 as 与 ! 1 2 3 4 5 6 const data = body as MyType ;const root = document .getElementById ('root' )!;
项目里 :
1 2 3 4 5 6 7 8 9 ReactDOM .createRoot (document .getElementById ('root' )!).render ( <React.StrictMode > <App /> </React.StrictMode > ); const body = (await res.json ()) as BaseResult <T>;
⚠️ 慎用 as,应该让 TS 自动推断。
2.10 联合类型 + 类型守卫 1 2 3 4 5 6 7 8 9 10 type Status = 'running' | 'completed' ;type Item = { type : 'thinking' ; content : string } | { type : 'tool' ; toolName : string };function handle (item : Item ) { if (item.type === 'thinking' ) { console .log (item.content ); } else { console .log (item.toolName ); } }
项目里 :
1 2 3 4 5 6 7 8 9 10 11 12 type TimelineItem = | { type : 'thinking' ; content : string } | { type : 'tool' ; toolName : string ; status : 'running' | 'completed' } | { type : 'error' ; message : string }; if (item.type === 'thinking' ) { } else if (item.type === 'tool' ) { }
3. 项目的类型层次(怎么看) 项目里类型分三层:
1 2 3 types/api.ts ← 后端接口的原始数据类型 store/chatStore.ts ← 前端用的领域类型(Chat, ChatMessage...) components/Xxx/Xxx.tsx ← 组件 Props 类型(紧邻组件定义)
例子:消息类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 interface MessageVO { id : number ; question : string | null ; answer : string | null ; thinking : string | null ; } interface ChatMessage { id : string ; role : 'user' | 'assistant' ; content : string ; timeline ?: TimelineItem []; } function mapSessionDetail (detail : SessionDetailVO ): ChatMessage [] { }
4. 完整例子:从接口定义到组件使用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 interface SessionListVO { conversationId : string ; question : string | null ; } interface Chat { id : string ; title : string ; messages : ChatMessage []; isNew : boolean ; } interface Props { chat : Chat ; active : boolean ; onSelect : (id : string ) => void ; } function ChatItem ({ chat, active, onSelect }: Props ) { return ( <div onClick ={() => onSelect(chat.id)}> {chat.title} </div > ); } <ChatItem chat={someChat} active={true } onSelect={handleSelect} />
5. 常见 TS 报错与解决 报错 原因 解决 Type 'string' is not assignable to type 'number'类型不匹配 改类型或改值 Object is possibly 'undefined'可能为 undefined 用 ?. 或 if 判断 Property 'xxx' does not exist on type 'Yyy'对象上没有该字段 检查拼写或加可选 ? Argument of type '...' is not assignable to parameter of type '...'函数参数类型不对 检查函数签名
6. 项目 TypeScript 配置(看个大概) 1 2 3 4 5 6 7 8 9 10 11 12 { "compilerOptions" : { "target" : "ES2020" , "lib" : [ "ES2020" , "DOM" ] , "jsx" : "react-jsx" , "strict" : true , "paths" : { "@/*" : [ "./src/*" ] } } }
关键配置 :
strict: true:开启所有严格检查(不要关闭)jsx: "react-jsx":启用 JSX 支持paths: { "@/*": ["./src/*"] }:启用 @/ 路径别名7. 一段话总结 TypeScript 给 JS 加了「类型」:标注变量类型、函数参数/返回值类型、对象形状。 项目里 80% 的 TS 语法就是:
interface 定义对象/Props 形状type 定义联合类型可选字段 ? 表示可能没有泛型 <T> 出现在 httpGet<T>、useState<T>、useRef<T> 中掌握这四点就能读懂 95% 的项目代码。
接下来 现在你已经熟悉 React 项目所需的全部基础(HTML/CSS/JS/TS)。 继续阅读 06-前端工具链npm与Vite.md ,理解 Vite、npm、import 解析等工具链概念。