⚡ 编程实验室🏗️ HTML🎨 CSS⚡ JavaScript🐍 Python🗄️ SQL☕ Java⚛️ React💚 Vue🟢 Node.js⚙️ C语言🐘 PHP🐹 Go🔷 TypeScript🐬 MySQL🔧 C++🎯 C#🦀 Rust🅱️ Bootstrap💡 jQuery🎸 Django🍃 MongoDB👗 Sass🎪 Kotlin📊 R语言📋 XML📊 Excel🐘 PostgreSQL🐳 Docker🅰️ Angular🎮 游戏🏠 网站首页

TS const 断言:让类型更精确

学习 TypeScript const 断言,用于创建只读和字面量类型。 · 难度:入门 · +15XP

const 断言的概念

as const 是 TypeScript 3.4 引入的断言方式,它告诉编译器将表达式推断为最具体的类型。它会将数组转换为只读元组,将对象属性转换为只读,并将所有值推断为字面量类型。

主要效果

特性不使用 as const使用 as const
数组string[]readonly ['a', 'b']
对象属性string | number字面量类型
可变性可修改只读

代码示例

// 不使用 as const
const colors = ['red', 'green', 'blue'];
// 类型:string[]

// 使用 as const const colorsConst = ['red', 'green', 'blue'] as const; // 类型:readonly ['red', 'green', 'blue']

// 对象示例 const config = { host: 'localhost', port: 3000 } as const; // config.host 类型:'localhost',而非 string // config.port 类型:3000,而非 number // config 所有属性均为 readonly

// 实际应用:创建枚举行为 type Direction = typeof colorsConst[number]; // 'red' | 'green' | 'blue'

function getColor(direction: Direction) { console.log(Color: ${direction}); }

getColor('red'); // 正确 // getColor('yellow'); // 错误

练习提示

使用 as const 定义一个状态数组 ['idle', 'loading', 'success', 'error'],然后提取出状态联合类型。编写一个函数,只接受这些状态作为参数,并输出对应的消息。

Ctrl+Enter
🚀 升级VIP
解锁全部课程+AI助手

🏆 学习排行

加载中...

📊 统计

📖 200 篇
0 完成
🔥 0