[英]better type safety for string key indexer in typescript
我已经创建了这个游乐场 ,这里是代码:
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");
ShortcutMap类型不能充分缩小联合类型。
是否可以通过某种方式缩小联合来获得更好的类型安全性。
我在这条线上出现错误:
return buildShortcuts(map);
类型'string |的参数 组合| 字符串[] | 顺序| 快捷方式 {[key:string]:快捷方式; }”不能分配给“快捷方式”类型的参数。 “字符串”类型不能分配给“快捷方式”类型。
我认为您造成类型混淆的部分原因是您将ShortcutMap定义为
export type ShortcutMap =
| {
[key: string]: Shortcut;
}
| Shortcut;
我希望在这里,地图只是
{
[key: string]: Shortcut;
}
一种解决方案是避免使用联合类型,使您的类型更明确/更窄。
看看这个TypeScript游乐场 。
希望有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.