typeScript 函数怎么根据参数对象中的布尔值状态返回具体类型?
问题描述
test函数无法根据参数对象中的布尔值状态返回具体类型
相关代码
interface Result {
isSuccess: boolean
}
interface Success {
success: string
}
interface Error {
error: string
}
function test(result: Result = { isSuccess: true }): Success
function test(result: Result = { isSuccess: false }): Error
function test(result: Result): unknown {
const success: Success = {
success: '成功'
}
const error: Error = {
error: '失败'
}
return result.isSuccess === true ? success : error
}
你期待的结果是什么?
我希望能够 isSuccess 为真的时候返回 Success 为假的时候返回 Error
回复
1个回答

test
2024-07-12
不能直接用 Error 当 interface,给你改了下名字
interface Result {
isSuccess: boolean
}
interface Success {
success: string
}
interface IError {
error: string
}
function test(result: { isSuccess: true }): Success
function test(result: { isSuccess: false }): IError
function test(result: Result): Success | IError {
const success: Success = {
success: '成功'
}
const error: IError = {
error: '失败'
}
return result.isSuccess === true ? success : error
}
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容