OiO.lk Blog javascript How to make a key optional in Union Type
javascript

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 created a mapping using the keys in Types for example

const MAPPING: { [key in Types]: string } = {
 APPLE: "Here is Apple",
 MANGO: "Here is Mango",
};

This code gives error it’s asking to define mapping for each key if I don’t do it gives error:

Property 'BANANA' is missing in type '{ APPLE: string; MANGO: string; }' but required in type '{ APPLE: string; MANGO: string; 
 BANANA: string; }'

To avoid these types of errors, I want to make the BANANA optional also I don’t want to change the MAPPING itself, it should remain as [key in Types]. I understand that either using Exclude or Types? would work but this requires changes in a lot of files.

Is there any other way to achieve this?



You need to sign in to view this answers

Exit mobile version