You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript如何从联合类型强制转换为指定子类型?

TypeScript类型转换问题解决方法

问题代码

type example = {
    name : string | number | null
}
type processNumber = {
    name : number
}
const a : example = {
    name : 123
} as const
function PROCESS (input : processNumber) {
    console.log(input.name)
}
PROCESS(a);

报错信息

Argument of type 'example' is not assignable to parameter of type 'processNumber'.
  Types of property 'name' are incompatible.
    Type 'string | number | null' is not assignable to type 'number'.
      Type 'null' is not assignable to type 'number'.

解决方案

1. 单个属性的强制转换

有两种直接实现方式:

  • 直接断言整个对象符合processNumber类型:
    PROCESS(a as processNumber);
    
  • 单独断言name属性后构造符合要求的对象:
    PROCESS({ name: a.name as number });
    

2. 多属性场景的快速内联转换

如果存在多个需要转换的属性,用对象展开+属性断言的方式可以快速生成符合目标类型的对象:

// 扩展示例:多属性场景
type example = {
    name : string | number | null,
    age: string | number | null
}
type processNumber = {
    name : number,
    age: number
}
const a : example = {
    name : 123,
    age: 25
} as const

// 内联一次性转换多个属性
PROCESS({
    ...a,
    name: a.name as number,
    age: a.age as number
});

如果要兼顾运行时类型安全(避免实际值不符合类型断言),可以添加类型守卫做前置检查:

function isProcessNumber(input: example): input is processNumber {
    return typeof input.name === 'number';
}

if (isProcessNumber(a)) {
    PROCESS(a); // 此时TypeScript会自动识别a符合processNumber类型
}

内容的提问来源于stack exchange,提问作者A. L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:20:23