【问题标题】:Typescript Playground Error on using generic type with Arrow function使用带有箭头函数的泛型类型的 Typescript Playground 错误
【发布时间】:2021-12-25 02:23:14
【问题描述】:

在使用带有箭头函数的泛型类型时,Typescript Playground 抛出错误Cannot find name 'T'

这里是link

function hasAllProperties <T>(obj: any, props: (keyof T)[]): obj is T {
    return props.every((prop) => obj.hasOwnProperty(prop))
}

// This throws error , wont compile 
const hasAllPropertiesArrow = <T>(obj: any, props: (keyof T)[]): obj is T => {
    return props.every((prop) => obj.hasOwnProperty(prop))
}

由于我是泛型类型的新手,我认为这不是 ts 操场的错误,而是我缺乏理解。 另外如何将普通函数重写为箭头函数?

【问题讨论】:

标签: typescript typescript-generics


【解决方案1】:

这是 TypeScript 解析器的设计限制;请参阅microsoft/TypeScript#15713 以获得权​​威答案。语法const x = &lt;T&gt;() 使编译器误以为&lt;T&gt;JSX 标记;您可以通过查看错误消息的其余部分来验证这一点,例如 JSX element 'T' has no corresponding closing tag.

如果您不需要 JSX/TSX 支持,您可以像在 this Playground link 中一样删除 the --jsx compiler option 设置。如果您确实需要 JSX 支持,那么您可以通过在引入 T 类型参数后使用尾随逗号来解决此问题:

const hasAllPropertiesArrow = <T,>(obj: any, props: (keyof T)[]): obj is T => {
    return props.every((prop) => obj.hasOwnProperty(prop))
}

这个逗号对代码的含义没有影响,但它可以防止解析器感到困惑。

Playground link to code

【讨论】:

    猜你喜欢
    • 2018-01-31
    • 2015-11-25
    • 2017-04-27
    • 2018-05-15
    • 2017-06-12
    • 2020-07-04
    • 1970-01-01
    • 2019-06-08
    相关资源
    最近更新 更多