Skip to content

Commit

Permalink
fix: a more accurate type for the Select onChange prop
Browse files Browse the repository at this point in the history
  • Loading branch information
haideralsh committed Jan 7, 2025
1 parent 1748158 commit 982871b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
4 changes: 2 additions & 2 deletions src/Select/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
} from "./SelectComponents";
import { SelectOption } from "./SelectOption";
import MenuList from "./MenuList";
import { calcOptionsLength, checkOptionsAreValid, extractValue, getReactSelectValue } from "./lib";
import { calcOptionsLength, checkOptionsAreValid, CustomOnChangeValue, extractValue, getReactSelectValue } from "./lib";

export type NDSOptionValue = string | number | boolean | null;

Expand All @@ -46,7 +46,7 @@ interface CustomProps<Option extends NDSOption, IsMulti extends boolean, Group e
defaultValue?: PropsValue<Option["value"]>;
value?: PropsValue<Option["value"]>;
options: readonly Option[];
onChange?: (newValue: PropsValue<Option["value"]>) => void;
onChange?: (newValue: CustomOnChangeValue<IsMulti>) => void;
windowThreshold?: number;
styles?: (selectStyles: StylesConfig<Option, IsMulti, Group>) => StylesConfig<Option, IsMulti, Group>;
}
Expand Down
16 changes: 9 additions & 7 deletions src/Select/lib.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as React from "react";
import { Options, PropsValue } from "react-select";
import { OnChangeValue, Options, PropsValue } from "react-select";
import { NDSOption, NDSOptionValue } from "./Select";

export function calcOptionsLength(options) {
Expand Down Expand Up @@ -92,20 +92,22 @@ export function getReactSelectValue(options: Options<NDSOption>, input: PropsVal
return getOption(options, input);
}

export function extractValue(
options: Options<NDSOption> | NDSOption,
isMulti: boolean
): NDSOptionValue[] | NDSOptionValue {
export type CustomOnChangeValue<IsMulti extends boolean> = IsMulti extends true ? NDSOptionValue[] : NDSOptionValue;

export function extractValue<IsMulti extends boolean>(
options: OnChangeValue<NDSOption, IsMulti>,
isMulti: IsMulti
): CustomOnChangeValue<IsMulti> {
if (options === null) {
return null;
}

if (!Array.isArray(options)) {
return (options as NDSOption).value;
return (options as NDSOption).value as CustomOnChangeValue<IsMulti>;
}

if (isMulti) {
return options && options.length ? options.map((o) => o.value) : [];
return (options && options.length ? options.map((o) => o.value) : []) as CustomOnChangeValue<IsMulti>;
}

throw new Error("UNEXPECTED ERROR: don't forget to enable isMulti");
Expand Down

0 comments on commit 982871b

Please sign in to comment.