Typescript. How to define that an object key is required but it could have 2 different naming?

Issue

Basically, I’m trying to handle the situation when I have the style object and this object must have either maxHeight or height properties. In this case, if some of those properties had been passed, the other one isn’t required anymore. However, I can’t find any possible way to do it via TS.
I tried to do it in this way however this solution doesn’t work, unfortunately

Example:

type Style = {
  ['maxHeight' | 'height': string]: string | number; 
 }

Many thanks for any help or the appropriate documentation link!

Solution

You can use a union type:

type Style = 
    | { maxHeight: string | number }
    | { height: string | number }
;

Answered By – Clashsoft

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published