mui / mui/material-ui

[Select] TypeScript example for Object values

Open
#29,969 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

scope: select support: question
Dominant language
JavaScript
Stars
99.1k
Forks
32.5k
Avg merge
2d 17h
Merged PRs (30d)
106

Description

Duplicates
  • I have searched the existing issues
Latest version
  • I have tested the latest version
Summary 💡

I would like to use an object as a value for my select field with TypeScript, without having to use IDs and going back and forth between index, string and object conversions.

I got a working example, but TypeScript still complains about incorrect typings.

Help would be greatly appreciated.

Examples 🌈

I couldn't find a decent template for MUI-5 + typescript, but here's the code example:

type ItemType = {
  myStr: string,
  myNbr: number,
  myBool: boolean
};

const items: ItemType[] = [
  {
    myStr: "myStr1",
    myNbr: 1,
    myBool: false
  },
  {
    myStr: "myStr2",
    myNbr: 2,
    myBool: true
  }
];

export default function Test() {
  const [selectedItem, setSelectedItem] =
    React.useState<ItemType | undefined>(undefined);

  return (
    <Select
      value={selectedItem}
      onChange={(selectEvent) => setSelectedItem(selectEvent.target.value)}
    >
      <MenuItem value={undefined}>All</MenuItem>
      {items.map((item) => (
        <MenuItem key={item.myStr} value={item}>{item.myStr}</MenuItem>
      ))}
    </Select>
  );
}

I'm getting errors, because onChange is expecting string | ItemType instead of undefined | ItemType and same error for MenuItem value.

Motivation 🔦

No response

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Select and MenuItem typings in the provided MUI 5 TypeScript example, focusing on the value and onChange types shown in the issue. Check that the example type-checks when selectedItem can be undefined or an ItemType, and that object values work without conversion.

Written by the indexing model from the issue text.

Assessment

Tech stack
react, typescript
Domain
frontend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.