打字稿对象 const 断言输入 - .includes() “'string' 类型的参数不能分配给 'never' 类型的参数。”

时间:2021-02-12 05:02:21

标签: javascript arrays typescript object typeerror

我有一个看起来像这样的对象,我想在其上使用 const 断言:

const animals = {
    birds: ['eagle', 'hawk', 'toucan'],
    reptiles: ['lizard', 'snake'],
    fish: ['clown fish', 'blue tang']
} as const;

然后,如果数组中存在特定字符串,我希望能够检查所有对象值,在这种情况下,我想获取属性键。我试图这样做:

const species = Object.entries(animals).find(x => x[1].includes('eagle'))[0];

但是,当尝试在 .includes() 方法内的 x[1] 的条目值(即条目值)上使用 .find() 时,它会给出错误 Argument of type 'string' is not assignable to parameter of type 'never'."

enter image description here

对于在这种情况下为什么 x[1] 具有 never 类型真的很困惑。任何有关如何解决此错误或获取匹配值的密钥的更好方法的任何想法都将不胜感激。

1 个答案:

答案 0 :(得分:0)

不定义数组类型,默认情况下永远不会。您需要做的就是将 x1 定义为字符串。