0

I don't understand the following code example:

IdType extends string

IdType consists out of several value types, how can it extend a string?

   const Select = <IdType extends string>(props: {
      options: Array<{
        id: IdType;
        name: string;
      }>;
      selectedItemId?: IdType;
      onSelect: (id: IdType) => void;
    }) => (
      <select
        value={props.selectedItemId ?? ''}
        onChange={e => props.onSelect(e.target.value as IdType)}
      >
        {props.options.map(option => (
          <option key={option.id} value={option.id}>
            {option.name}
          </option>
        ))}
      </

select>
);
vuvu
  • 4,886
  • 12
  • 50
  • 73
  • Does this answer your question? [Extending a string in TypeScript](https://stackoverflow.com/questions/57342018/extending-a-string-in-typescript) – Joachim Sauer Apr 30 '21 at 09:42

1 Answers1

1

This makes sure this won't compile because you're not accepting any string, but one very specific string:

Select<'mystring'>({
  options: [{
    id: 'invalid', // fails
    name: 'name'
  }],
  selectedItemId: 'mystring', // OK
  onSelect: (id: string) => {}
});
Lmbrtz
  • 91
  • 6