Home > Software design >  Expect a nested property in a templated function parameter that depends on the template type
Expect a nested property in a templated function parameter that depends on the template type

Time:04-29

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.

(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.

CodePudding user response:

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

  • Related