Hello, I've got a function named createBreakpointValue
that accepts an Object with arguments: desktop, tablet, mobile, allElse
The specific logic I need is as follows:
If all arguments are provided (desktop, tablet, mobile
), then the allElse
argument should be ignored and an error should occur if allElse
is included.
If only some arguments are passed (such as mobile
), then the allElse
argument must be required alongside either desktop & tablet
.
This is my current implementation:
type ValueOf<T> = T[keyof T];
type Points =
| {
desktop: any;
tablet: any;
mobile: any;
allElse?: never;
}
| {
desktop?: any;
tablet?: any;
mobile?: any;
allElse: any;
};
const currentViewport: keyof Points = "desktop";
const createBreakpointValue = (points: Points): ValueOf<Points> => {
if (currentViewport in points) {
return points[currentViewport];
} else {
return points.allElse;
}
};
// valid usage
createBreakpointValue({ allElse: 1 });
//valid usage
createBreakpointValue({ desktop: 1, tablet: 1, mobile: 1 });
// should highlight allElse as invalid
createBreakpointValue({ allElse: 1, desktop: 1, mobile: 1, tablet: 1 });
// should indicate that allElse or mobile must be provided
createBreakpointValue({ desktop: 1, tablet: 1 });
Currently, the typing works correctly up to when all correct arguments and allElse are passed which should prompt a message like "allElse is not valid here".
Sandbox: https://codesandbox.io/s/lucid-breeze-zlgws0?file=/src/index.ts