#How to fix here : TS2339: Property length does not exist on type never

2 messages · Page 1 of 1 (latest)

tawny oar
#

Hello, how can I fix typesript error here ?
"TS2339: Property length does not exist on type never"

import { appendResponseHeader, H3Event } from 'h3'

export default defineNuxtPlugin(async (nuxtApp) => {
    const auth = useAuthStore()

    var setCookies: string[] | null = null

    if (!auth.csrfToken) {
        await useFetch('http://localhost:8000/sanctum/csrf-cookie', {
            headers: {
                Accept: 'application/json',
            },
            credentials: 'include',
            onResponse: (response) => {
                setCookies = response.response.headers.getSetCookie() as string[]
            },
        })

        // here the ts error
        if (setCookies && setCookies.length > 0) {
            for (let index in setCookies) {
                appendResponseHeader(
                    useRequestEvent(),
                    'set-cookie',
                    setCookies[index]
                )
            }
        }
    }
})
tender galleon
#

TS doesn't track side effects across functions, so it thinks setCookies is definitely null, you can get around that by using a type assertion instead of a type annotation:

let setCookies = null as string[] | null