Skip to content

Commit 5859c1f

Browse files
authored
Add generics for inferring value type (#32)
1 parent 5440399 commit 5859c1f

File tree

1 file changed

+11
-10
lines changed

1 file changed

+11
-10
lines changed

src/SelectInput.tsx

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,12 +9,12 @@ import type {Props as IndicatorProps} from './Indicator';
99
import Item from './Item';
1010
import type {Props as ItemProps} from './Item';
1111

12-
interface Props {
12+
interface Props<V> {
1313
/**
1414
* Items to display in a list. Each item must be an object and have `label` and `value` props, it may also optionally have a `key` prop.
1515
* If no `key` prop is provided, `value` will be used as the item key.
1616
*/
17-
items?: Item[];
17+
items?: Array<Item<V>>;
1818

1919
/**
2020
* Listen to user's input. Useful in case there are multiple input components at the same time and input must be "routed" to a specific component.
@@ -48,21 +48,22 @@ interface Props {
4848
/**
4949
* Function to call when user selects an item. Item object is passed to that function as an argument.
5050
*/
51-
onSelect?: (item: Item) => void;
51+
onSelect?: (item: Item<V>) => void;
5252

5353
/**
5454
* Function to call when user highlights an item. Item object is passed to that function as an argument.
5555
*/
56-
onHighlight?: (item: Item) => void;
56+
onHighlight?: (item: Item<V>) => void;
5757
}
5858

59-
export interface Item {
59+
export interface Item<V> {
6060
key?: string;
6161
label: string;
62-
value: unknown;
62+
value: V;
6363
}
6464

65-
const SelectInput: FC<Props> = ({
65+
// eslint-disable-next-line react/function-component-definition
66+
function SelectInput<V>({
6667
items = [],
6768
isFocused = true,
6869
initialIndex = 0,
@@ -71,14 +72,14 @@ const SelectInput: FC<Props> = ({
7172
limit: customLimit,
7273
onSelect,
7374
onHighlight
74-
}) => {
75+
}: Props<V>): JSX.Element {
7576
const [rotateIndex, setRotateIndex] = useState(0);
7677
const [selectedIndex, setSelectedIndex] = useState(initialIndex);
7778
const hasLimit =
7879
typeof customLimit === 'number' && items.length > customLimit;
7980
const limit = hasLimit ? Math.min(customLimit!, items.length) : items.length;
8081

81-
const previousItems = useRef<Item[]>(items);
82+
const previousItems = useRef<Array<Item<V>>(items);
8283

8384
useEffect(() => {
8485
if (!isEqual(previousItems.current, items)) {
@@ -173,6 +174,6 @@ const SelectInput: FC<Props> = ({
173174
})}
174175
</Box>
175176
);
176-
};
177+
}
177178

178179
export default SelectInput;

0 commit comments

Comments
 (0)