skip to Main Content

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?

2

Answers


  1. const MAPPING: { [key in Types]?: number } = { APPLE: 1 };
    
    Login or Signup to reply.
  2. You could use an intersection:

    Playground

    export type Types = "APPLE" | "MANGO" | "BANANA";
    
    type MakeOptional<T extends string, E extends string, V = any> = {
        [K in Exclude<T, E>]: V
    } & {
        [K in E]?: V
    };
    
    type Mapped = MakeOptional<Types, 'BANANA', string>
    
    const MAPPING: Mapped = {
     APPLE: "Here is Apple",
     MANGO: "Here is Mango",
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search