javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > TypeScript 字面量类型

TypeScript之字面量类型的使用详解

作者:无风听海

在TypeScript中,字面量类型是值级别的类型,表示某个值本身就是类型的一部分,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

✳️ 一、什么是字面量类型(Literal Types)?

在 TypeScript 中,字面量类型(Literal Types)是值级别的类型,表示某个值本身就是类型的一部分。

常见的字面量类型包括:

字面量类型举例
数字1, 42, 0
字符串"hello", "yes"
布尔true, false

这些类型只接受对应的字面值:

type A = 1;
const x: A = 1;       // ✅ 合法
const y: A = 2;       // ❌ 报错:不能赋值 number 给类型 1

🧠 为什么要有字面量类型?

字面量类型让我们可以更严格、更精确地控制值的合法性。

比如在按钮组件中:

type ButtonSize = 'small' | 'medium' | 'large';

function createButton(size: ButtonSize) { ... }

createButton('medium'); // ✅
createButton('huge');   // ❌ 类型错误

✳️ 二、字面量类型 VS 基础类型的区别

字面量类型宽泛基础类型
'hello'string
1number
trueboolean

你可以认为字面量类型是基础类型的“子类型”。

let a: 'yes' = 'yes';       // ✅
let b: string = 'yes';      // ✅
a = b;                      // ❌ string 可能不等于 'yes'
b = a;                      // ✅ 'yes' 一定是 string

✳️ 三、什么时候会推断为字面量类型?

这是关键!我们来看 TypeScript 中推断为字面量类型的几种情况

✅ 1.const声明的变量,会推断为字面量类型

const a = 42;       // 推断为 42(字面量类型)
let b = 42;         // 推断为 number(更宽泛)
const s = "hello";  // 推断为 "hello"
let t = "hello";    // 推断为 string

🧠 原理: const 声明表示变量值不可变,所以可以精确地推断为值本身的类型。

✅ 2. 使用as const明确指定字面量类型

const arr = [1, 2, 3] as const;
// 推断为 readonly [1, 2, 3] (字面量元组)
const obj = {
  type: 'success',
  code: 200,
} as const;
// 推断为 { readonly type: 'success'; readonly code: 200 }

📌 as const 是字面量推断的强制方式,常用于需要精准类型的地方,比如 Redux、API 返回值、类型映射。

✅ 3. 明确写了字面量类型

当然,最直接的方法就是你直接指定类型:

let status: 'loading' | 'done' = 'loading';

❌ 不会推断为字面量类型的情况

情况推断类型原因
let a = 42;number因为 let 变量是可变的
const a = someFunc();非字面量如果返回值无法静态分析成字面量
const obj = { key: 'value' };{ key: string }对象属性默认是宽泛类型,除非加 as const

✳️ 四、推断字面量类型的实际应用场景

1. 联合类型的类型保护

type Action = 'increment' | 'decrement';

function reducer(action: Action) {
  if (action === 'increment') {
    // ✅ Narrowing to 'increment'
  }
}

2. 字面量值作为 discriminated union 的 tag

type Shape =
  | { kind: 'circle'; radius: number }
  | { kind: 'square'; side: number };

function getArea(shape: Shape) {
  if (shape.kind === 'circle') {
    return Math.PI * shape.radius ** 2;
  }
}

3. 使用as const提供精确值类型

const options = ['up', 'down'] as const;
type Direction = typeof options[number]; // 'up' | 'down'

✅ 总结:字面量类型核心知识表

知识点说明
字面量类型定义1, "hi", true 等
推断为字面量的条件const 声明、as const、手动指定字面量类型
推断不会是字面量的情况let、函数返回值、普通对象/数组字面量
实际用途更精确的类型检查、discriminated union、配置常量、枚举替代等

到此这篇关于TypeScript之字面量类型的使用详解的文章就介绍到这了,更多相关TypeScript 字面量类型内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文