From 4d1189641bd4866425a1596bd59021db64b22bf5 Mon Sep 17 00:00:00 2001 From: AnsonH Date: Wed, 28 Dec 2022 17:08:05 +0800 Subject: [PATCH] refactor: stronger TypeScript typing --- src/index.tsx | 17 +++++++++-------- src/tag.tsx | 4 ++-- src/use-did-update-effect.tsx | 7 +++++-- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index b535239..680d5ec 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -11,7 +11,7 @@ export interface TagsInputProps { placeHolder?: string; value?: string[]; onChange?: (tags: string[]) => void; - onBlur?: any; + onBlur?: React.FocusEventHandler; separators?: string[]; disableBackspaceRemove?: boolean; onExisting?: (tag: string) => void; @@ -44,22 +44,23 @@ export const TagsInput = ({ onKeyUp, classNames, }: TagsInputProps) => { - const [tags, setTags] = useState(value || []); + const [tags, setTags] = useState(value || []); useDidUpdateEffect(() => { onChange && onChange(tags); }, [tags]); useDidUpdateEffect(() => { - if (JSON.stringify(value) !== JSON.stringify(tags)) { + if (value && JSON.stringify(value) !== JSON.stringify(tags)) { setTags(value); } }, [value]); - const handleOnKeyUp = e => { + const handleOnKeyUp: React.KeyboardEventHandler = e => { e.stopPropagation(); - const text = e.target.value; + const target = e.target as HTMLInputElement; + const text = target.value; if ( !text && @@ -67,7 +68,7 @@ export const TagsInput = ({ tags.length && e.key === "Backspace" ) { - e.target.value = isEditOnRemove ? `${tags.at(-1)} ` : ""; + target.value = isEditOnRemove ? `${tags.at(-1)} ` : ""; setTags([...tags.slice(0, -1)]); } @@ -80,11 +81,11 @@ export const TagsInput = ({ return; } setTags([...tags, text]); - e.target.value = ""; + target.value = ""; } }; - const onTagRemove = text => { + const onTagRemove = (text: string) => { setTags(tags.filter(tag => tag !== text)); onRemoved && onRemoved(text); }; diff --git a/src/tag.tsx b/src/tag.tsx index ed10d09..4b44e81 100644 --- a/src/tag.tsx +++ b/src/tag.tsx @@ -3,13 +3,13 @@ import cc from "./classnames"; interface TagProps { text: string; - remove: any; + remove: (tag: string) => void; disabled?: boolean; className?: string; } export default function Tag({ text, remove, disabled, className }: TagProps) { - const handleOnRemove = e => { + const handleOnRemove: React.MouseEventHandler = e => { e.stopPropagation(); remove(text); }; diff --git a/src/use-did-update-effect.tsx b/src/use-did-update-effect.tsx index b76db14..59e97f0 100644 --- a/src/use-did-update-effect.tsx +++ b/src/use-did-update-effect.tsx @@ -1,10 +1,13 @@ import { useEffect, useRef } from "react"; -export function useDidUpdateEffect(fn, inputs) { +export function useDidUpdateEffect( + fn: () => void, + inputs: ReadonlyArray +) { const didMountRef = useRef(false); useEffect(() => { if (didMountRef.current) fn(); else didMountRef.current = true; }, inputs); -} \ No newline at end of file +}