Skip to content

Instantly share code, notes, and snippets.

Avatar

David Gilbertson davidgilbertson

  • Sydney, Australia
View GitHub Profile
View Select.tsx
type Nullable<IdType, RequiredType> = RequiredType extends true ? IdType : IdType | null;
export type SelectProps<IdType extends string, RequiredType extends boolean> = {
options: Array<{id: IdType; name: string}>;
selectedItemId: Nullable<IdType, RequiredType>;
onSelect: (id: Nullable<IdType, RequiredType>) => void;
required?: RequiredType;
};
const Select = <IdType extends string, RequiredType extends boolean>(
View SelectConsumer.tsx
<Select
selectedItemId={selectedItemId}
onSelect={setSelectedItemId}
options={[
{value: Size.Small, children: 'Small'},
{value: Size.Medium, children: 'Medium'},
{value: Size.Large, children: 'Large', disabled: true},
]}
required
/>
View Select.tsx
type Nullable<IdType, RequiredType> = RequiredType extends true ? IdType : IdType | null;
type OptionProps<IdType> = React.ComponentProps<'option'> & {
value: IdType;
};
const Select = <IdType extends string, RequiredType extends boolean>(props: {
options: Array<OptionProps<IdType>>;
selectedItemId: Nullable<IdType, RequiredType>;
onSelect: (id: Nullable<IdType, RequiredType>) => void;
View Select.tsx
type BaseProps<IdType> = {
options: Array<{id: IdType; name: string}>;
};
type PropsWhenOptional<IdType> = BaseProps<IdType> & {
required?: false;
selectedItemId?: IdType | null;
onSelect: (id: IdType | null) => void;
};
View makeBigger.ts
const makeBigger = <T extends string | number>(stringOrNumber: T) => {
if (typeof stringOrNumber === 'string') {
return stringOrNumber.toUpperCase();
}
return (stringOrNumber * 4);
};
View makeBigger.ts
const makeBigger = (stringOrNumber: string | number) => {
if (typeof stringOrNumber === 'string') {
return stringOrNumber.toUpperCase();
}
return stringOrNumber * 4;
};
View Select.tsx
type Nullable<IdType, RequiredType> = RequiredType extends true
? IdType
: IdType | null;
const Select = <IdType extends string, RequiredType extends boolean>(props: {
options: Array<{id: IdType; name: string}>;
selectedItemId: Nullable<IdType, RequiredType>;
onSelect: (id: Nullable<IdType, RequiredType>) => void;
required?: RequiredType;
}) => (
View Select.tsx
type BaseEntityWithFancyId<IdType> = {
id: IdType;
name: string;
};
const Select = <IdType extends string>(props: {
options: Array<BaseEntityWithFancyId<IdType>>;
selectedItemId?: IdType;
onSelect: (id: IdType) => void;
}) => (
View Select.tsx
const Select = <IdType extends string>(props: {
options: Array<{
id: IdType;
name: string;
}>;
selectedItemId?: IdType;
onSelect: (id: IdType) => void;
}) => (
<select
value={props.selectedItemId ?? ''}
View SelectConsumer.tsx
<Select
onSelect={id => {
// Do something with id
}}
options={[
{id: Size.Small, name: 'Small'},
{id: Size.Medium, name: 'Medium'},
{id: Size.Large, name: 'Large'},
]}
/>