Skip to content

Commit

Permalink
add types to useCookie hook
Browse files Browse the repository at this point in the history
added strict types fixes #291 with help and reference of microsoft/TypeScript#20965 (comment)
  • Loading branch information
amaster507 authored Aug 6, 2021
1 parent 07c0e7e commit 3f59f99
Showing 1 changed file with 10 additions and 10 deletions.
20 changes: 10 additions & 10 deletions packages/react-cookie/src/useCookies.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ import { useContext, useEffect, useState, useRef, useMemo } from 'react';
import { Cookie, CookieSetOptions } from 'universal-cookie';
import CookiesContext from './CookiesContext';

export default function useCookies(
dependencies?: string[]
export default function useCookies<T extends string, U = {[K in T]?: string}>(
dependencies?: T[]
): [
{ [name: string]: any },
(name: string, value: Cookie, options?: CookieSetOptions) => void,
(name: string, options?: CookieSetOptions) => void
U,
(name: T, value: Cookie, options?: CookieSetOptions) => void,
(name: T, options?: CookieSetOptions) => void
] {
const cookies = useContext(CookiesContext);
if (!cookies) {
Expand All @@ -23,7 +23,7 @@ export default function useCookies(
const newCookies = cookies.getAll();

if (
shouldUpdate(
shouldUpdate<T|null,U>(
dependencies || null,
newCookies,
previousCookiesRef.current
Expand All @@ -48,10 +48,10 @@ export default function useCookies(
return [allCookies, setCookie, removeCookie];
}

function shouldUpdate(
dependencies: string[] | null,
newCookies: { [name: string]: any },
oldCookies: { [name: string]: any }
function shouldUpdate<T extends string, U = {[K in T]?: string}>(
dependencies: T[] | null,
newCookies: U,
oldCookies: U
) {
if (!dependencies) {
return true;
Expand Down

0 comments on commit 3f59f99

Please sign in to comment.