OiO.lk Blog javascript Typescript: How to make a key optional in Union Type
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

Exit mobile version