You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何TypeScript中属性名无法被识别为string类型?

TypeScript泛型函数筛选string类型属性名的类型问题

我需要编写一个泛型函数,用来处理任意接口/类(通过泛型参数传入)的string类型属性名,最初的代码如下:

function doSomething<T extends object>(props: (keyof T)[]) {
    for (let prop of props) {
        const x: string = prop;
    }
}

这段代码触发了TS2322错误:Type 'string | number | symbol' is not assignable to type 'string',这是因为keyof T的类型可能是string、number或symbol三种类型之一,无法直接赋值给string类型变量。

为了筛选出string类型的属性名,我添加了typeof prop === 'string'的类型判断,修改后的代码如下:

function doSomething<T extends object>(props: (keyof T)[]) {
    for (let prop of props) {
        if (typeof prop === 'string') {
            const x: string = prop;
        }
    }
}

但此时WebStorm工具提示**"Invalid 'typeof' check: 'prop' cannot have type 'string'"**,错误认为prop不可能是string类型。不过实际在Jest测试中,传入的prop确实是string类型,这个问题经确认是WebStorm的WEB-49787 bug导致的。

内容的提问来源于stack exchange,提问作者F-H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 13:20:16