当前位置: 首页 > news >正文

Typescript -字面量类型

在 TypeScript 中,​​字面量类型(Literal Types)​​ 是一种将​​具体的值作为类型​​的机制,用于限制变量或参数只能接受特定的字面量值。它通过精确约束取值范围,增强代码的类型安全性

  • 基础定义与类型​​
    字面量类型分为三种:
  • 字符串字面量类型​​:如 “success”、“error”
  • ​数字字面量类型​​:如 0、1、42
  • ​布尔字面量类型​​:true 或 false(实际使用较少)
// 字符串字面量类型
type Status = "success" | "error";
let status: Status = "success"; // 只能赋值 "success" 或 "error"// 数字字面量类型
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6;
const roll: DiceRoll = 3; // 只能赋值 1-6// 布尔字面量类型(通常直接使用 boolean)
type IsReady = true;
let ready: IsReady = true; // 只能为 true
  • 字面量类型的联合类型
    字面量类型可以与其他字面量类型或原始类型联合使用,形成更灵活的类型定义。
type Color = 'red' | 'green' | 'blue';
type Size = 'small' | 'medium' | 'large';type ProductFilter = Color | Size;function applyFilter(filter: ProductFilter) {console.log(`Applying filter: ${filter}`);
}applyFilter('red'); // 正确
applyFilter('small'); // 正确
applyFilter('extra-large'); // 错误:Argument of type '"extra-large"' is not assignable to parameter of type 'ProductFilter'.
  • 字面量类型与对象字面量
    在对象字面量中使用字面量类型,可以确保对象的属性只能是特定的值。
type Role = 'admin' | 'user' | 'guest';interface User {name: string;role: Role;
}const user: User = {name: 'John Doe',role: 'admin' // 正确
};const user2: User = {name: 'Jane Doe',role: 'moderator' // 错误:Type '"moderator"' is not assignable to type 'Role'.
};
  • 字面量类型与函数参数
    在函数参数中使用字面量类型,可以限制函数调用时传入的参数值。
type LogLevel = 'info' | 'warning' | 'error';function log(message: string, level: LogLevel = 'info') {console.log(`[${level.toUpperCase()}] ${message}`);
}log('Application started'); // [INFO] Application started
log('File not found', 'warning'); // [WARNING] File not found
log('Critical error', 'critical'); // 错误:Argument of type '"critical"' is not assignable to parameter of type 'LogLevel'.
  • 字面量类型与类型守卫
    字面量类型可以与类型守卫结合使用,以便在函数内部进行更精确的类型检查。

type FileType = 'image' | 'video' | 'audio';function processFile(file: { type: FileType; data: any }) {if (file.type === 'image') {console.log('Processing image:', file.data);} else if (file.type === 'video') {console.log('Processing video:', file.data);} else if (file.type === 'audio') {console.log('Processing audio:', file.data);}
}processFile({ type: 'image', data: 'image.jpg' }); // 正确
processFile({ type: 'document', data: 'document.pdf' }); // 错误:Argument of type '"document"' is not assignable to parameter of type 'FileType'.
  • 字面量类型与映射类型
    字面量类型可以用于映射类型中,以创建灵活的类型转换。

type Key = 'name' | 'age' | 'email';type PartialUser<T> = {[K in Key]?: T;
};const user: PartialUser<string> = {name: 'John Doe',age: '30', // 错误:Type 'string' is not assignable to type 'number'.email: 'john@example.com'
};
  • 字面量类型与模板字面量类型
    字面量类型可以和其他字符串结合,形成模板字面量类型,用于生成新的类型。
type EventNames = 'click' | 'hover' | 'submit';
type EventCallback = (event: Event) => void;type EventListenerMap = {[K in EventNames]: EventCallback;
};const listeners: EventListenerMap = {click: (event) => console.log('Click event', event),hover: (event) => console.log('Hover event', event),submit: (event) => console.log('Submit event', event)
};
  • 字面量类型与 as const 断言
    as const 断言可以与字面量类型结合使用,确保变量的值不会被修改,并且类型被精确推断。
const directions = ['North', 'South', 'East', 'West'] as const;
type Direction = typeof directions[number]; // "North" | "South" | "East" | "West"function move(direction: Direction) {console.log(`Moving ${direction}`);
}move('North'); // 正确
move('Northeast'); // 错误:Argument of type '"Northeast"' is not assignable to parameter of type 'Direction'.
http://www.dtcms.com/a/273670.html

相关文章:

  • Linux的基础I/O
  • 买小屏幕的时候注意避坑
  • [Java 17] 无模版动态生成 PDF:图片嵌入与动态表格渲染实战
  • Linux磁盘限速(Ubuntu24实测)
  • 算法学习笔记:17.蒙特卡洛算法 ——从原理到实战,涵盖 LeetCode 与考研 408 例题
  • cnpm exec v.s. npx
  • C语言常见面试知识点详解:从入门到精通
  • 亿级流量下的缓存架构设计:Redis+Caffeine多级缓存实战
  • Web安全 - 基于 SM2/SM4 的前后端国产加解密方案详解
  • Flutter优缺点
  • Java学习第三十二部分——异常
  • 【爬虫】- 爬虫原理及其入门
  • 【批量文件查找】如何从文件夹中批量搜索所需文件复制到指定的地方,一次性查找多个图片文件并复制的操作步骤和注意事项
  • 基于Python的豆瓣图书数据分析与可视化系统【自动采集、海量数据集、多维度分析、机器学习】
  • 从Excel到PDF一步到位的台签打印解决方案
  • 学习笔记(34):matplotlib绘制图表-房价数据分析与可视化
  • Java小白-String
  • Allegro 17.4操作记录
  • 平板柔光屏与镜面屏的区别有哪些?技术原理与适用场景全解析
  • 飞算JavaAI:重构Java开发的“人机协同”新范式
  • Python数据读写与组织全解析(查缺补漏篇)
  • 使用Spring Boot和PageHelper实现数据分页
  • 【MySQL】———— 索引
  • 【字节跳动】数据挖掘面试题0016:解释AUC的定义,它解决了什么问题,优缺点是什么,并说出工业界如何计算AUC。
  • 【理念●体系】从零打造 Windows + WSL + Docker + Anaconda + PyCharm 的 AI 全链路开发体系
  • SQL开窗函数
  • 5G IMS注册关键一步:UE如何通过ePCO获取P-CSCF地址
  • 微服务引擎 MSE 及云原生 API 网关 2025 年 6 月产品动态
  • 拓扑排序之 leetcode 207.课程表
  • 突破分子设计瓶颈:融合bVAE与GPU伊辛机的智能优化策略