1

I'm trying to build an interface, for example, Dropdown props interface for React component, and I'm trying to make params optional only if T generic is string. My research found zero answers for my question.

enter image description here

as you can see here, I'm trying to make getTemplate optional only if T extends string type, but if it something else I will have to write it.

Unfortunately it doesn't work. param with undefined type is not optional parameter, it is parameter with undefined.

Any suggestions? Thanks ahead.

here an example of something I tried but doesn't work:

type Props<T extends string | Omit<any, 'string'>> = (T extends string
? {}
: {
      getTemplate: (item: T) => ReactNode;
      getDisplayTemplate(item: T): ReactNode;
      getItemIdentifier(item: T): string | number;
  }) & {
items: Array<T>;
disabled?: boolean;
className?: string;
placeholder?: string;
selectedItems: Array<T>;
isMultiSelect?: boolean;
onChange(items: Array<T>): void;

};

export const Dropdown = <T,>({
disabled,
placeholder,
selectedItems = [],
items,
onChange,
getDisplayTemplate,
getItemIdentifier,
getTemplate,
isMultiSelect,
className,

}: Props) => {

2
  • Please paste your original code next time instead of using image. Commented Dec 1, 2021 at 8:01
  • Noted, thanks will be done next time. I'll edit the post right now Commented Dec 1, 2021 at 9:12

1 Answer 1

1

Maybe extract the conditional part into a member of a union type. Make getTemplate, etc. optional only if T is a string.

type ConditionalProps<T> = {
      getTemplate: (item: T) => ReactNode;
      getDisplayTemplate(item: T): ReactNode;
      getItemIdentifier(item: T): string | number;
};
type Props<T> =
(T extends string ? Partial<ConditionalProps<T>> : ConditionalProps<T>) & {
    items: Array<T>;
    disabled?: boolean;
    className?: string;
    placeholder?: string;
    selectedItems: Array<T>;
    isMultiSelect?: boolean;
    onChange(items: Array<T>): void;
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the comment, I tried it but I think it doesnt work also. I can't extract the functions when i use the componet
@EdenBinyamin It's difficult to help you without seeing the code and the actual error, but if you type the props with a type parameter like props: Props<MyClass>, you should be able to access props.getTemplate.
wrote it on the post itself, sorry man

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.