TypeScript 01:类型注解与类型推断

TypeScript 01:类型注解与类型推断

有 JS 基础即可阅读。

1. TS 是什么

TS = JS + 类型系统 :类型只在写代码时检查,运行前被剥掉,跑的还是 JS。

价值就一条:把运行时的 bug 提前到写代码时报错。

ts 复制代码
// JS: add(1, '2') 静默返回 '12',bug 潜伏到线上
// TS: add(1, '2') 直接标红,不让提交

2. 类型注解

冒号 + 类型,标注「这个值是什么」:

ts 复制代码
let username: string = 'Tom'
let age: number = 18 // 没有 int/float,统一 number
let isVip: boolean = false
let nothing: null = null

3. 类型推断:大多数注解不用写

右边是什么,左边就是什么,能推断就不写:

ts 复制代码
let price = 99 // 自动推断为 number
price = '便宜点' // ❌ Type 'string' is not assignable to type 'number'

只有 3 种情况必须手写注解:

场景 原因
函数参数 TS 猜不到调用方传什么
空容器 let list = [] 没内容可推断
导出的 API 锁定「契约」,防止乱传

4. 数组

ts 复制代码
const scores: number[] = [90, 85, 77]
const tags: Array<string> = ['new', 'hot'] // 等价于 string[]
const mixed: (string | number)[] = ['a', 1]

scores.push('90') // ❌ 每个元素都必须是 number

5. 对象:描述「形状」

ts 复制代码
const user: { name: string; age: number } = { name: 'Tom', age: 18 }

const u = { name: 'Jerry' } // ❌ Property 'age' is missing(少字段)
user.age = '十九' // ❌ string 不能赋给 number(类型错)

6. 函数

参数必须标,返回值让 TS 推断:

ts 复制代码
function add(a: number, b: number) {
  return a + b // 返回值自动推断为 number
}
const greet = (name: string) => `你好,${name}` // 推断为 string

add(1, '2') // ❌ 参数类型不符(JS 里会静默返回 '12')
add(1, 2, 3) // ❌ Expected 2 arguments, but got 3(个数也管)

7. 联合类型 A | B

「可能是 A,也可能是 B」:

ts 复制代码
function formatId(id: string | number) {
  return `ID-${id}`
}
formatId(101) // ✅
formatId(true) // ❌ boolean 不在联合范围内

拿到联合类型后想分开处理,需要「类型收窄」(typeof 判断等)。

8. any:逃生舱,少用

ts 复制代码
const data: any = JSON.parse('{"x":1}')
data.x
data.foo.bar.baz() // ✅ 全不检查,错了运行时才炸

any = 关闭检查。更安全的替代品是 unknown(用之前必须先确认类型)。

9. 高频报错速查

报错 人话
Type 'string' is not assignable to type 'number' 塞了字符串,这里要数字
Property 'age' is missing 对象缺字段
Expected 2 arguments, but got 3 参数个数不对
相关推荐
总要学点什么1 天前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
2601_962885721 天前
quotes 字段全解:涨跌幅、振幅、换手率的口径与单位
java·前端·spring
excel1 天前
encodeURI 和 encodeURIComponent 有什么区别?
前端
前端精髓1 天前
调用openrouter的免费API模型
java·前端·javascript
赛博守夜人1 天前
AI安全攻防与治理之十四:AI 安全测试不能脱离传统安全,Web、API、移动端与模型攻击面的组合拳
前端·人工智能·安全
开开心心_Every1 天前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
networknomad1 天前
OpenReplay:自己搭的会话回放工具,给前端排错用的
前端·其他
缓慢更新1 天前
AI 辅助生成单测:从接口定义到用例的流水线
java·服务器·前端·网络·数据库·人工智能
陈随易1 天前
AI 运维服务器,安全又可靠的方法
前端·后端·程序员
风骏时光牛马1 天前
AI稳定性治理体系构建与疑难问题深度分析
前端