Skip to content

Commit

Permalink
style: strong type
Browse files Browse the repository at this point in the history
  • Loading branch information
askwuxue committed Jun 27, 2023
1 parent c5d7cc4 commit 81489f3
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
6 changes: 3 additions & 3 deletions packages/hooks/src/useFavicon/__tests__/index.test.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { renderHook } from '@testing-library/react';
import useFavicon from '../index';
import useFavicon, { HrefType } from '../index';

describe('useFavicon', () => {
it('should set the favicon', () => {
Expand All @@ -9,7 +9,7 @@ describe('useFavicon', () => {
});

it('should support svg/png/ico/gif', () => {
const { rerender } = renderHook((url: string) => useFavicon(url));
const { rerender } = renderHook((url: HrefType) => useFavicon(url));
const suffixs = ['svg', 'png', 'ico', 'gif'];
const imgTypeMap = {
svg: 'image/svg+xml',
Expand All @@ -18,7 +18,7 @@ describe('useFavicon', () => {
png: 'image/png',
};
suffixs.forEach((suffix) => {
const url = `favicon.${suffix}`;
const url: HrefType = `favicon.${suffix as 'svg' | 'png' | 'ico' | 'gif'}`;
rerender(url);
const link = document.querySelector("link[rel*='icon']") as HTMLLinkElement;
expect(link).toHaveAttribute('type', imgTypeMap[suffix]);
Expand Down
3 changes: 2 additions & 1 deletion packages/hooks/src/useFavicon/demo/demo1.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@

import React, { useState } from 'react';
import { useFavicon } from 'ahooks';
import { HrefType } from '..';

export const DEFAULT_FAVICON_URL = 'https://ahooks.js.org/simple-logo.svg';

export const GOOGLE_FAVICON_URL = 'https://www.google.com/favicon.ico';

export default () => {
const [url, setUrl] = useState<string>(DEFAULT_FAVICON_URL);
const [url, setUrl] = useState<HrefType>(DEFAULT_FAVICON_URL);

useFavicon(url);

Expand Down
6 changes: 5 additions & 1 deletion packages/hooks/src/useFavicon/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,11 @@ const ImgTypeMap = {

type ImgTypes = keyof typeof ImgTypeMap;

const useFavicon = (href: string) => {
export type HrefType = `${string}.${any extends ImgTypes | Lowercase<ImgTypes>
? ImgTypes | Lowercase<ImgTypes>
: null}`;

const useFavicon = (href: HrefType) => {
useEffect(() => {
if (!href) return;

Expand Down

0 comments on commit 81489f3

Please sign in to comment.