Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Using TypeScript Enum in Dropdown - What's an elegant way to append an "all" value?

$
0
0

I have a lookup model being delivered via a REST API that I need to bind to a drop down.The TypeScript model from the API is effectively

export interface ResponsibilitiesLookupModel {    id: Responsibilities;    name: string;    description?: string | undefined;}export enum Responsibilities {    Default = "Default",    Clerk = "Clerk",    Manager = "Manager",    // and so on}

After fetching the result from the API, I want to include an "All" option and invoke special logic when this option is selected. Below is the fetch from the server and the inclusion of the All option (this is React, btw).

    const result = await client.responsibilities();    setResponsibilities([      {        id: 'All',        name: 'All',        description: 'All',      },      ...result,    ]);

The TS compiler rightly complains about the all option Type '"All"' is not assignable to type 'Responsibilities'.

And further down the code, when checking whether the selected id is All (or a constant/enum equivalent), the TS compiler rightly complains This condition will always return 'false' since the types 'Responsibilities' and '"All" have no overlap.'

I know I can "extend" an enum by creating a new type and bind to that.

type SelectedResponsibilityType = AllType | Responsibilities;

But doing so means I essentially need to bind to a newly define type instead of ResponsibilitiesLookupModel which is just a pain.

Is there a more elegant way to approach this?


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>