Discover and explore this online TypeScript playground where code magic happens:
export enum KeyCode {
Alt = 'meta',
Command = 'command',
// etc.
}
export type KeyStroke = KeyCode | string;
export interface Combination {
combination: KeyStroke[];
}
export interface Sequence {
sequence: KeyStroke[];
}
export type ShortcutItem = KeyStroke | KeyStroke[] | Combination | Sequence;
export interface Shortcut {
[key: string]: ShortcutItem;
}
export type ShortcutMap =
| {
[key: string]: Shortcut;
}
| Shortcut;
export const buildShortcuts = (map: Shortcut) => {
return []
}
function getShortcuts(shortcutMap: ShortcutMap, mapKey?: keyof typeof shortcutMap){
const map = mapKey ? shortcutMap[mapKey] : shortcutMap;
return buildShortcuts(map);
}
export const shortcutMapWithoutKey: ShortcutMap = {
MOVE_LEFT: [KeyCode.Alt, 'a'],
MOVE_RIGHT: [KeyCode.Command, 'd'],
};
export const shortcutMapWithKey: ShortcutMap = {
one: {
MOVE_UP: [KeyCode.Alt, 'b'],
MOVE_DOWN: [KeyCode.Command, 'e'],
},
two: {
MOVE_HERE: [KeyCode.Alt, 'c'],
MOVE_THERE: [KeyCode.Command, 'f'],
}
};
const a = getShortcuts(shortcutMapWithoutKey);
const b = getShortcuts(shortcutMapWithKey, "one");
The current implementation of the ShortcutMap type may need further refinement to enhance union type narrowing.
Do you think there's a way to achieve better type safety by narrowing down the union?
An error is reported on this line:
return buildShortcuts(map);
Argument of type 'string | Combination | string[] | Sequence | Shortcut | { [key: string]: Shortcut; }' cannot be assigned to parameter of type 'Shortcut'. The type 'string' is not compatible with type 'Shortcut'.