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

TypeScript报错求助:类型不匹配与属性不存在等问题解析

TypeScript报错解析与修复

错误1:TS2339 - 'signIn'/'signOut' 属性不存在于类型 'UserType | null'

原因

AuthContext 被错误定义为 UserType | null 类型,但实际通过 AuthContext.Provider 传入的是包含 signIn、signOut 和 user 的对象,类型完全不匹配。调用 useAuth() 时,TypeScript 认为返回值是 UserType | null,自然找不到 signIn/signOut 方法。

修复步骤

  1. 定义正确的上下文类型,包含所需方法和用户状态:
type AuthContextType = {
  signIn: () => void;
  signOut: () => void;
  user: UserType | null;
};
  1. 更新上下文创建代码,使用新类型并设置合理默认值:
const AuthContext = React.createContext<AuthContextType>({
  signIn: () => {},
  signOut: () => {},
  user: null,
});

错误2:TS7006 - 参数 'props' 隐式具有 'any' 类型

原因

AuthProvider 函数的 props 参数未指定类型,TypeScript 默认将其视为 any,违反严格类型检查规则。

修复步骤

给 props 添加 React.PropsWithChildren 类型,明确它包含 children 属性:

export function AuthProvider(props: React.PropsWithChildren) {
  // 原有逻辑保留
}

错误3:TS2345 - 'UserType | null' 类型无法赋值给 'UserType' 类型

原因

useProtectedRoute 的参数被定义为 UserType,但调用时传入的 user 状态是 UserType | null,null 类型不满足参数要求。

修复步骤

更新 useProtectedRoute 的参数类型,允许传入 UserType | null(函数内部已经处理了 !user 的逻辑):

function useProtectedRoute(user: UserType | null) {
  // 原有逻辑保留
}

完整修复后的 context/auth.tsx 代码

import { router, useSegments } from 'expo-router';
import React from 'react';

type UserType = {}

// 定义正确的上下文类型
type AuthContextType = {
  signIn: () => void;
  signOut: () => void;
  user: UserType | null;
};

// 创建上下文并设置默认值
const AuthContext = React.createContext<AuthContextType>({
  signIn: () => {},
  signOut: () => {},
  user: null,
});

export function useAuth() {
  return React.useContext(AuthContext);
}

// 更新参数类型为 UserType | null
function useProtectedRoute(user: UserType | null) {
  const segments = useSegments();

  React.useEffect(() => {
    const inAuthGroup = segments[0] === '(auth)';

    if (
      !user &&
      !inAuthGroup
    ) {
      router.replace('/register');
    } else if (user && inAuthGroup) {
      router.replace('/');
    }
  }, [user, segments]);
}

// 给 props 添加类型
export function AuthProvider(props: React.PropsWithChildren) {
  const [user, setAuth] = React.useState<UserType | null>(null);

  useProtectedRoute(user);

  return (
    <AuthContext.Provider
      value={{
        signIn: () => setAuth({}),
        signOut: () => setAuth(null),
        user,
      }}>
      {props.children}
    </AuthContext.Provider>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:37:43