首页 > 解决方案 > 打字稿类型字符串不可分配给类型 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),因为我会失去类型保护。

标签: typescript

解决方案


使用枚举的解决方案是一个很好的解决方案,我建议您使用它。

您收到错误的原因是打字稿不会为 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

推荐阅读