Actualmente tengo un método que se ve así, que usa nextjs/auth para iniciar sesión con las credenciales de un formulario. Sin embargo, recibo un error de verificación de tipo 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); } };Yo (más o menos) entiendo por qué, si el resultado == indefinido, entonces result.status podría ser potencialmente indefinido y hey ho ERROR. Multa. Entonces pruebo esto:
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); } }; Luego obtengo que Property 'status' does not exist on type 'never'.ts(2339) if (result && 'status' in result && result.status === 200 && result.ok) { pero esto tampoco funciona. ¿Alguien sabe qué estoy haciendo mal aquí para que Typescript funcione bien?
Debajo del capó, la definición de inicio de sesión (del tercero next-auth.js se ve así por cierto:
export declare function signIn<P extends RedirectableProviderType | undefined = undefined>(provider?: LiteralUnion<BuiltInProviderType>, options?: SignInOptions, authorizationParams?: SignInAuthorisationParams): Promise<P extends RedirectableProviderType ? SignInResponse | undefined : undefined>;Actualización para Googlers.
Tipo de respuesta incorrecto: SignInResponse no SignInOptions
Solución:
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) {Me quedé atrapado aquí también. Nada parecía hacer feliz a TypeScript aquí por completo.
Su solución actualizada en la descripción original todavía me da: "La propiedad 'ok' no existe en el tipo 'nunca'". errores
Esto fue lo único que funcionó para mí:
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;Una forma es pasar las 'credenciales' de RedirectableProviderType como un tipo
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'); }