Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Expect a nested property in a templated function parameter that depends on the template type

I want the "options" property of the parameter object to at least contain the "label" property.

I tried doing it on my own, but it won’t compile.

interface BaseOptionType {
  label: string;
}

interface CreatableAutoCompleteProps<OptionType extends BaseOptionType> {
  name?: string;
  options: OptionType;
}

const CreatableAutoComplete = <_OptionType,>({
  name,
  options,
}: CreatableAutoCompleteProps<_OptionType>): number => {
  return 0;
};

export default CreatableAutoComplete;

I receive the following error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(type parameter) _OptionType in <_OptionType>({ name, options, }: CreatableAutoCompleteProps<_OptionType>): number

Type '_OptionType' does not satisfy the constraint 'BaseOptionType'.ts(2344)

So, what would be the correct way to do this.

>Solution :

Type ‘_OptionType’ does not satisfy the constraint ‘BaseOptionType’

Well, I think you just need to make _OptionType extend BaseOptionType.

const CreatableAutoComplete = <_OptionType extends BaseOptionType,>({
  name,
  options,
}: CreatableAutoCompleteProps<_OptionType>): number => {
  return 0;
};

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading