Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created September 12, 2017 06:50
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save joduplessis/7b3b4340353760e945f972a69e855d11 to your computer and use it in GitHub Desktop.
Save joduplessis/7b3b4340353760e945f972a69e855d11 to your computer and use it in GitHub Desktop.
Setting, deleting and retrieving cookies in Typescript.
@michael-freidgeim-webjet

I tried https://gist.github.com/floriancastelain/4a6063edd927c59351b43fa1b3f57b94 version, but have the same error, that original gist has
[tsl] ERROR in c:common\cookieUtils.ts(20,16)
TS2532: Object is possibly 'undefined'.
Adding if (!parts) return null doesn't help.
Only // @ts-ignore before return parts.pop(). helps

@wellingtonfds
Copy link

thanks guy!!

@ricocheting
Copy link

The error Object is possibly 'undefined' appears to be from typescript thinking .pop() can return an undefined result (even though the length check should prevent that).

For me it goes away with:

if (parts.length === 2) {
	const ppop = parts.pop();
	if (ppop) {
		return ppop.split(";").shift();
	}
}

@tp00012x
Copy link

You are missing the return type for getCookie.

@benediktvaldez
Copy link

Just commenting to say that with the latest typescript you could solve the pop undefined scenario like this

export function getCookie(name: string) {
    const value = "; " + document.cookie;
    const parts = value.split("; " + name + "=");
    
    if (parts.length == 2) {
        return parts.pop()?.split(";").shift();
    }
}

Alternatively if you'd like to consistently return a string you could do it like this

  return (
    (parts.length === 2 &&
      parts
        .pop()
        ?.split(";")
        .shift()) ||
    ""
  );

@kittanat-mos
Copy link

thank you krub

@AbbottF
Copy link

AbbottF commented May 14, 2022

Thank you. This has helped me weening myself from jQuery Libraries...and morphing my js to ts.

@mctrafik
Copy link

mctrafik commented May 3, 2023

For those seeing this thread in 2023, getting a cookie can be implemented as

const getCookie = (cookieName: string) => new RegExp(`${cookieName}=([^;]+);`).exec(document.cookie)?.[1];

which IMHO is more elegant than shifting values out of an array and splitting out all cookie entries first.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment