【问题标题】:Typescript object const assertion typing - .includes() "Argument of type 'string' is not assignable to parameter of type 'never'."Typescript object const assertion typing - .includes() “'string' 类型的参数不可分配给'never' 类型的参数。”
【发布时间】:2021-05-15 21:25:40
【问题描述】:

我有一个看起来像这样的对象,我想在上面使用 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];

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

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

【问题讨论】:

    标签: javascript arrays typescript object typeerror


    【解决方案1】:

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

    【讨论】:

    • 你能详细说明我将如何去做吗?当我查看 x[1] 的隐式类型时,它显示了它的 (property) 1: readonly ["eagle", "hawk", "toucan"] | readonly ["lizard", "snake"] | readonly ["clown fish", "blue tang"],我认为这没问题?
    猜你喜欢
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2023-02-18
    • 2021-04-27
    • 2021-08-20
    相关资源
    最近更新 更多