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 | 类型的参数 组合 | 字符串[] | 序列 | 快捷方式 | { [键:字符串]:快捷方式;}' 不可分配给“快捷方式”类型的参数。类型“字符串”不可分配给类型“快捷方式”。
解决方案
I think part of your type confusion comes from the fact that you define your ShortcutMap as
export type ShortcutMap =
| {
[key: string]: Shortcut;
}
| Shortcut;
I would expect here, that a map is just
{
[key: string]: Shortcut;
}
One solution for you would be to make your types more explicit/narrow by avoiding the union type.
Have a look at this TypeScript playground.
Hope, that helps.
推荐阅读
- swift - 如何在 swift 中将委托值添加到 tableview
- c# - 从 libgit2sharp 中的 git 配置中获取用户的身份/签名以进行提交
- python - 想要在第 3 列中识别具有相同值的行并将它们分组到输出中
- r - 过滤包含重要单核苷酸多态性的基因
- saml-2.0 - 单点注销如何与 OKTA(IDP)-Shibboleth(SP)-App 配合使用
- java - 如何在 Spring Boot 中对两个实体进行内部连接?
- javascript - 用于匹配第一个单词的正则表达式
- autodesk-forge - 尝试使用 Autodesk Forge ReCap API 重建特定数量的图像时出错
- python - TypeError:左操作数必须是 str
- postfix-mta - 带有多个接收字段的电子邮件标头:这怎么会发生,可以用来对抗垃圾邮件