Skip to content

Instantly share code, notes, and snippets.

@hunan-rostomyan
Created July 19, 2016 22:49
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save hunan-rostomyan/28e8702c1cecff41f7fe64345b76f2ca to your computer and use it in GitHub Desktop.
Save hunan-rostomyan/28e8702c1cecff41f7fe64345b76f2ca to your computer and use it in GitHub Desktop.
Get a cookie by name in TypeScript
// Given a cookie key `name`, returns the value of
// the cookie or `null`, if the key is not found.
function getCookie(name: string): string {
const nameLenPlus = (name.length + 1);
return document.cookie
.split(';')
.map(c => c.trim())
.filter(cookie => {
return cookie.substring(0, nameLenPlus) === `${name}=`;
})
.map(cookie => {
return decodeURIComponent(cookie.substring(nameLenPlus));
})[0] || null;
}
@gustavonecore
Copy link

Since the value could be null, you should define that in the return type ;)

getCookie(name: string): string|null {

Thanks for sharing!

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