October 25, 2024
Chicago 12, Melborne City, USA
javascript

Typescript: How to make a key optional in Union Type


I have a type in my typescript project

export type Types = "APPLE" | "MANGO" | "BANANA";

Here I want the BANANA to be optional, i.e

if I have create mapping using the keys in Types for example

const MAPPING: { [key in Types] ....

this asked me to define mapping for each key if I don’t do it gives error: "Property BANANA is missing in type ……"

to avoid these types of errors

I want to make the BANANA optional also I don’t want to change the MAPPING fn itself, it should remain as [key in Types].

is there any way to achieve this?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video