TypeScript联合类型无法访问非公共属性问题求助
解决方案:缩小联合类型范围以访问专属属性
你的问题本质是TypeScript在处理联合类型时,只能保证访问所有类型共有的属性。要访问user_tokens_info这类专属属性,需要通过类型缩小明确当前值的具体类型,以下是几种可行方案:
1. 自定义类型谓词(推荐)
针对你的三个返回类型,编写自定义类型守卫函数,帮助TypeScript判断当前值的具体类型:
首先补充AuthUnHandleError的类型定义(假设它包含独有的标识字段):
export type AuthUnHandleError = { type: 'auth-unhandled-error'; router: string; message: string; };
然后编写类型守卫函数:
// 判断是否为UserTokens类型 function isUserTokens(res: UserTokens | AuthError | AuthUnHandleError): res is UserTokens { return (res as UserTokens).user_tokens_info !== undefined; } // 判断是否为AuthError类型 function isAuthError(res: UserTokens | AuthError | AuthUnHandleError): res is AuthError { return (res as AuthError).errors !== undefined; } // 判断是否为AuthUnHandleError类型 function isAuthUnHandleError(res: UserTokens | AuthError | AuthUnHandleError): res is AuthUnHandleError { return (res as AuthUnHandleError).type === 'auth-unhandled-error'; }
使用时通过条件判断缩小类型:
const response = await userTokens(yourAccessToken); if (isUserTokens(response)) { // 此处TypeScript确定response为UserTokens类型,可直接访问user_tokens_info console.log(response.user_tokens_info); } else if (isAuthError(response)) { // 处理AuthError逻辑 console.log(response.errors); } else { // 处理未捕获错误逻辑 console.log(response.router); }
2. 判别式联合类型(更优雅的方案)
给每个返回类型添加一个唯一的判别字段(比如type),让TypeScript自动完成类型缩小:
修改类型定义:
export type AuthError = { type: 'auth-error'; // 新增判别字段 status: number | string; statusText: string; url: string; action: string; message: string; system: string; errors: Array<any> | []; } export interface UserTokens extends AuthNormalOutPut { type: 'user-tokens'; // 新增判别字段 user_tokens_info: Array<{ access_expires_in: number; create_time: number; last_used: number; os: string; tokenType: 'refresh' | 'access'; // 避免和外层type字段冲突,修改字段名 }>; } export type AuthUnHandleError = { type: 'auth-unhandled-error'; router: string; message: string; };
使用时通过switch语句自动推断类型:
const response = await userTokens(yourAccessToken); switch(response.type) { case 'user-tokens': // 自动推断为UserTokens类型 console.log(response.user_tokens_info); break; case 'auth-error': // 自动推断为AuthError类型 console.log(response.errors); break; case 'auth-unhandled-error': // 自动推断为AuthUnHandleError类型 console.log(response.router); break; }
3. 类型断言(不推荐,仅用于确定类型的场景)
如果你能100%确定当前返回值是UserTokens类型,可以直接用类型断言跳过TypeScript检查,但这种方式存在运行时风险:
const response = await userTokens(yourAccessToken); const userTokensInfo = (response as UserTokens).user_tokens_info;
内容的提问来源于stack exchange,提问作者Shahryar Tavakkoli
相关产品推荐
相关产品推荐

