繁体   English   中英

Typescript 错误:属性“status”在类型“never”上不存在。ts(2339)

[英]Typescript error: Property 'status' does not exist on type 'never'.ts(2339)

我目前有一个看起来像这样的方法,它使用nextjs/auth使用表单中的凭据登录。 但是,我收到类型检查错误Object is possibly 'undefined'.ts(2532)

const doStuff = async (values: any) => {
    const result: SignInOptions | undefined = await signIn('credentials', {
      redirect: false,
      password: values.pass,
      email: values.email,
    });
    if (result.status === 200 && result.ok) {
      await asyncDispatcher(
        loginUser({
          email: values.email,
          password: values.pass,
        }),
      );
      router.push(props.redirectLocation);
    }
  };

我(有点)明白为什么,如果 result == undefined 那么 result.status 可能是未定义的,嘿嘿错误。 美好的。 那么我试试这个:

const doStuff = async (values: any) => {
    const result: SignInOptions | undefined = await signIn('credentials', {
      redirect: false,
      password: values.pass,
      email: values.email,
    });
    if (result && result.status === 200 && result.ok) {
      await asyncDispatcher(
        loginUser({
          email: values.email,
          password: values.pass,
        }),
      );
      router.push(props.redirectLocation);
    }
  };

然后我得到Property 'status' does not exist on type 'never'.ts(2339)所以我尝试隐式检查键if (result && 'status' in result && result.status === 200 && result.ok) {但这也不起作用。 任何人都知道我在这里做错了什么让 Typescript 玩得开心?

在引擎盖下,登录的定义(来自第三方 next-auth.js 看起来像这样顺便说一句:

export declare function signIn<P extends RedirectableProviderType | undefined = undefined>(provider?: LiteralUnion<BuiltInProviderType>, options?: SignInOptions, authorizationParams?: SignInAuthorisationParams): Promise<P extends RedirectableProviderType ? SignInResponse | undefined : undefined>;

谷歌员工更新。

错误的响应类型 - SignInResponse 不是 SignInOptions

解决方案:

const result: SignInResponse | undefined = await signIn<'credentials'>('credentials', {
      redirect: false,
      password: values.pass,
      email: values.email,
    });
    if (result && 'status' in result && result.status === 200 && result.ok) {

我也卡在这里了。 似乎没有什么能让 TypeScript 在这里完全开心。

您在原始描述中更新的解决方案仍然给我:“'never' 类型不存在属性'ok'。” 错误。

这是唯一对我有用的东西:

import type {SignInResponse} from 'next-auth/react';
import {signIn} from 'next-auth/react';

const result = await signIn('credentials', {
    email: data.email,
    password: data.password,
    redirect: false,
}) as unknown as SignInResponse;

一种方法是将RedirectableProviderType 'credentials' 作为类型传入

    const result: SignInResponse | undefined = await signIn<'credentials'>(
  'credentials',
  {
    redirect: false,
    email: enteredEmail,
    password: enteredPassword,
  }
);

if (!!result && result.error) {
  // set some auth state
  router.replace('/account');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM