typescript - 打字稿类型字符串不可分配给类型 keyof
问题描述
我有以下代码:
const KeyboardEventKeys = {
Escape: 'Escape',
Enter: 'Enter',
Tab: 'Tab'
};
type KeyboardEventKeys = keyof (typeof KeyboardEventKeys);
function doSomething(key: KeyboardEventKeys) {}
当我将对象属性之一的值传递给函数时,它会对我大喊:
doSomething(KeyboardEventKeys.Enter);
一种解决方案是 cast as KeyboardEventKeys
,但它是一种多余的解决方案。没有它我怎么办?
我也不想添加doSomething(key: KeyboardEventKeys | string)
,因为我会失去类型保护。
解决方案
使用枚举的解决方案是一个很好的解决方案,我建议您使用它。
您收到错误的原因是打字稿不会为 const 成员推断字符串文字类型。您可以在创建时强制编译器通过使用额外的函数来推断字符串文字类型const
:
function createEnum<T extends { [P in keyof T]: P }>(o: T) {
return o
}
const KeyboardEventKeys = createEnum({ // typed as { Escape: "Escape"; Enter: "Enter"; Tab: "Tab"; }
Escape: 'Escape',
Enter: 'Enter',
Tab: 'Tab'
});
type KeyboardEventKeys = keyof (typeof KeyboardEventKeys);
function doSomething(key: KeyboardEventKeys) { }
doSomething("Enter")
doSomething("") //err
推荐阅读
- python - 递归导入所有接口实现并在 Python3 中实例化它们
- wordpress - 他们如何在他们的网站上播放这些电视频道?
- selenium - 如何加载由 selenium 在非自动化会话中收集的 cookie?
- python - 谁能用python解释我这个(hackerrank问题)?
- web-scraping - 使用 find_all 的 P 类是空的,即使它在那里
- getstream-io - 测试聊天推送通知时出现 BadDeviceToken 错误
- laravel - 在 Laravel-VueJS 中为不同的路由加载不同的刀片
- javascript - 使用 Jest 测试 React 组件时出现 UnhandledPromiseRejectionWarning
- ruby - 为什么这个 ruby 语法在这个例子中有效?
- go - 在golang中重用进程来持久化环境变量