Setting, deleting and retrieving cookies in Typescript.
You are missing the return type for getCookie
.
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()) ||
""
);
thank you krub
Thank you. This has helped me weening myself from jQuery Libraries...and morphing my js to ts.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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: