如何在独立函数中使用AWS-Amplify的Auth?解决TypeScript类型问题
问题
问题描述
在独立的helper.ts文件的函数中使用AWS-Amplify的Auth时触发错误。
使用方式
employerID: Auth.user.attributes["custom:id"],
错误信息
Property 'user' is private and only accessible within class 'AuthClass'.ts(2341)
目前临时做法是在页面主文件中将Auth作为参数传递给函数,例如await listEmployerImagesDetails(Auth);,但函数内的Auth被定义为any类型,丢失了TypeScript的类型安全特性。
完整代码示例(helpers.ts)
export const listEmployerImagesDetails = async(Auth: any, nextToken: string) => { try { const images = await API.graphql({ employerID: Auth.user.attributes["custom:id"], // 其他配置... }, }); return {/* 返回数据 */} } catch (error){ // 错误处理... } };
疑问
- 如何在独立函数中正确使用
Auth?(优先方案) - 如果上述方案不可行,如何通过
AuthClass确保传递Auth的类型正确性并利用TypeScript的类型安全?
解决方案
方案一:直接在独立函数中使用Auth(优先选择)
不要直接访问私有属性Auth.user,改用AWS Amplify Auth提供的公开方法Auth.currentAuthenticatedUser()获取当前用户信息。这是官方推荐的公开API,能安全获取用户属性,同时避免私有属性访问限制。
修改后的helper.ts代码:
// 先引入Auth import { Auth } from 'aws-amplify'; export const listEmployerImagesDetails = async(nextToken: string) => { try { // 获取当前认证用户 const currentUser = await Auth.currentAuthenticatedUser(); const employerID = currentUser.attributes["custom:id"]; const images = await API.graphql({ employerID: employerID, // 其他配置... }, }); return {/* 返回数据 */} } catch (error){ // 错误处理... } };
修改后无需在调用时传递Auth实例,直接在函数内部通过公开API获取用户信息,既符合规范又保证代码稳定性。
方案二:传递Auth并保证类型安全
如果必须传递Auth实例,不要用any类型,直接导入AuthClass作为类型注解:
import { Auth, AuthClass } from 'aws-amplify'; export const listEmployerImagesDetails = async(Auth: AuthClass, nextToken: string) => { try { // 依然使用公开方法获取用户,避免访问私有属性 const currentUser = await Auth.currentAuthenticatedUser(); const employerID = currentUser.attributes["custom:id"]; const images = await API.graphql({ employerID: employerID, // 其他配置... }, }); return {/* 返回数据 */} } catch (error){ // 错误处理... } };
调用时保持await listEmployerImagesDetails(Auth);即可,此时TypeScript会自动校验Auth的类型,提供类型提示和安全检查。
注意:无论哪种方案,都不要直接访问Auth.user私有属性——AWS Amplify的私有属性可能随版本更新变动,使用公开API才能保证代码长期稳定。
内容的提问来源于stack exchange,提问作者Luke
相关产品推荐
相关产品推荐

