Skip to content

Commit

Permalink
feat(type): value support generics
Browse files Browse the repository at this point in the history
  • Loading branch information
madocto committed Jan 20, 2024
1 parent ff3c898 commit 01ccaa4
Showing 1 changed file with 29 additions and 13 deletions.
42 changes: 29 additions & 13 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,31 @@ export type SegmentedValue = string | number;

export type SegmentedRawOption = SegmentedValue;

export interface SegmentedLabeledOption {
export interface SegmentedLabeledOption<ValueType = SegmentedRawOption> {
className?: string;
disabled?: boolean;
label: React.ReactNode;
value: SegmentedRawOption;
value: ValueType;
/**
* html `title` property for label
*/
title?: string;
}

type SegmentedOptions = (SegmentedRawOption | SegmentedLabeledOption)[];

export interface SegmentedProps
extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange'> {
options: SegmentedOptions;
defaultValue?: SegmentedValue;
value?: SegmentedValue;
onChange?: (value: SegmentedValue) => void;
type SegmentedOptions<T = SegmentedRawOption> = (
| T
| SegmentedLabeledOption<T>
)[];

export interface SegmentedProps<ValueType = SegmentedValue>
extends Omit<
React.HTMLProps<HTMLDivElement>,
'defaultValue' | 'value' | 'onChange'
> {
options: SegmentedOptions<ValueType>;
defaultValue?: ValueType;
value?: ValueType;
onChange?: (value: ValueType) => void;
disabled?: boolean;
prefixCls?: string;
direction?: 'ltr' | 'rtl';
Expand All @@ -46,7 +52,9 @@ function getValidTitle(option: SegmentedLabeledOption) {
}
}

function normalizeOptions(options: SegmentedOptions): SegmentedLabeledOption[] {
function normalizeOptions(
options: SegmentedProps['options'],
): SegmentedLabeledOption[] {
return options.map((option) => {
if (typeof option === 'object' && option !== null) {
const validTitle = getValidTitle(option);
Expand Down Expand Up @@ -219,6 +227,14 @@ const Segmented = React.forwardRef<HTMLDivElement, SegmentedProps>(
},
);

Segmented.displayName = 'Segmented';
if (process.env.NODE_ENV !== 'production') {
Segmented.displayName = 'Segmented';
}

const TypedSegmented = Segmented as <ValueType>(
props: SegmentedProps<ValueType> & {
ref?: React.ForwardedRef<HTMLDivElement>;
},
) => ReturnType<typeof Segmented>;

export default Segmented;
export default TypedSegmented;

0 comments on commit 01ccaa4

Please sign in to comment.