TypeScript的union类型

什么是 TypeScript 的联合类型(union type)?

TypeScript 的联合类型允许一个变量可以存储多种类型的值。比如,变量可以是 numberstring,也可以是 numberstringboolean 等多种类型之一。使用联合类型可以提升类型安全,避免 any 带来的潜在问题。


为什么需要联合类型?

在实际开发中,有些函数的参数可能既可以是数字,也可以是字符串:

function add(a: any, b: any) {
    if (typeof a === 'number' && typeof b === 'number') {
        return a + b;
    }
    if (typeof a === 'string' && typeof b === 'string') {
        return a.concat(b);
    }
    throw new Error('Parameters must be numbers or strings');
}

如果参数类型用 any,TypeScript 编译时不会报错,但运行时可能出错(比如传入 boolean)。这时就需要联合类型来限制参数类型,提高类型安全。


如何在 TypeScript 中声明联合类型?

可以使用 |⁠ 符号将多种类型组合。例如:

let result: number | string;
result = 10;      // 合法
result = 'Hi';    // 合法
result = false;   // 不合法,编译报错

如何用联合类型改进函数参数的类型安全?

将函数参数类型从 any 改为联合类型,例如对上面 add() 进行联合类型改造:

function add(a: number | string, b: number | string) {
    if (typeof a === 'number' && typeof b === 'number') {
        return a + b;
    }
    if (typeof a === 'string' && typeof b === 'string') {
        return a.concat(b);
    }
    throw new Error('Parameters must be numbers or strings');
}

这样,只有传入 numberstring 类型的参数才会通过编译,其他类型会报错。


联合类型的实际应用场景有哪些?

  • 需要函数参数或变量可以接受多种类型的值时
  • 处理多种输入类型但逻辑类似的场景
  • 增强类型安全,减少运行时错误

  • 如果你觉得我的工作对你有帮助,可以通过分享和推荐这篇文字或者关注同名公众号来支持我,你的支持是我持续创作的最大动力:
    image

  • 转载以及引用请注明原文链接

  • 本博客所有文章除特别声明外,均采用CC 署名-非商业使用-相同方式共享 许可协议。

posted @ 2025-06-10 17:30  Asanwos  阅读(5)  评论(0)    收藏  举报