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

如何基于输入参数为TypeScript函数定义条件返回类型?

让TypeScript识别函数根据参数返回特定类型的解决方案

问题场景

我需要实现一个函数,根据传入的参数类型返回对应特定类型的值,但TypeScript抛出了类型不匹配的错误。代码示例及报错如下:

type A = 'a'
type B = 'b'

const func = <Type extends A | B>(arg: Type): Type extends A ? 'a1': 'b1' => {
    // Type '"a1"' is not assignable to type 'Type extends "a" ? "a1" : "b1"'.(2322)
    if (arg === 'a') return 'a1'
     
    // Type '"b1"' is not assignable to type 'Type extends "a" ? "a1" : "b1"'.(2322)
    return 'b1'
}

// 期望返回类型为'a1'
const a1 = func('a')
// 期望返回类型为'b1'
const b1 = func('b')

解决方案

方法1:使用类型断言

直接为返回值添加类型断言,明确告诉TypeScript当前返回值符合泛型条件类型:

type A = 'a'
type B = 'b'

const func = <Type extends A | B>(arg: Type): Type extends A ? 'a1' : 'b1' => {
    if (arg === 'a') return 'a1' as Type extends A ? 'a1' : 'b1'
    return 'b1' as Type extends A ? 'a1' : 'b1'
}

const a1 = func('a') // 类型为'a1'
const b1 = func('b') // 类型为'b1'

方法2:使用函数重载(推荐)

通过函数重载明确不同参数对应的返回类型,TypeScript能直接匹配参数与返回值的对应关系,避免泛型条件类型的推断盲区:

type A = 'a'
type B = 'b'

// 重载签名:定义参数与返回值的对应关系
function func(arg: A): 'a1';
function func(arg: B): 'b1';
// 实现签名:处理具体逻辑
function func(arg: A | B) {
    if (arg === 'a') return 'a1'
    return 'b1'
}

const a1 = func('a') // 类型为'a1'
const b1 = func('b') // 类型为'b1'

方法3:使用satisfies关键字(TypeScript 4.9+)

如果使用TS 4.9及以上版本,可以用satisfies约束函数实现符合预期的类型签名,同时保留自动推断能力:

type A = 'a'
type B = 'b'
// 定义预期的函数类型
type FuncType = <Type extends A | B>(arg: Type) => Type extends A ? 'a1' : 'b1'

const func = ((arg) => {
    if (arg === 'a') return 'a1'
    return 'b1'
}) satisfies FuncType

const a1 = func('a') // 类型为'a1'
const b1 = func('b') // 类型为'b1'

报错原因说明

原代码中,TypeScript在检查函数体时无法将具体的'a1'/'b1'与泛型条件类型关联。因为泛型Type只有在函数调用时才会确定具体类型,函数内部的分支判断无法让TS确认当前分支对应的Type范围,因此抛出类型不匹配的错误。

内容的提问来源于stack exchange,提问作者Philiiiiiipp

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 12:32:46