在 for ... in 循环中输入推断 [英] Type inference in for ... in loop

查看:33
本文介绍了在 for ... in 循环中输入推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript 的推理非常好.但是,这个例子没有按预期工作,需要一个 //@ts-ignore.

TypeScript's inference is very good. However, this example does not work as expected and needs a //@ts-ignore.

for (const p in obj) {
    if (p !== 'staticCounter' && p !== 'staticProperty') {
        //@ts-ignore
        delete obj[p];
    }
}

没有忽略,我得到了错误

Without ignore, I get the error

const p: string 元素隐式具有任何"类型,因为'string' 类型的表达式不能用于索引类型 'Obj'.不在类型上找到带有字符串"类型参数的索引签名'对象'.ts(7053)

const p: string Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Obj'. No index signature with a parameter of type 'string' was found on type 'Obj'.ts(7053)

obj 是类型

interface Obj {
    a?: string;
    o?: string;
    b?: string;
    ...
}

虽然这个想法很容易掌握,但我认为在 TypeScript 中实现并不容易.一个可以是 obj 的键"类型不是类型系统支持的.

While the idea is easy to grasp, I think it will not be easy to implement into TypeScript. A "Can be a key for obj" type is not what the type system supports.

但这对我来说可以改进吗?我不喜欢 //@ts-ignores.

But can this be improved on my side? I don't like //@ts-ignores.

寻找其他方法来实现相同的目标.我选择了这种方式,因为事实证明它比创建一个新对象并为其分配两个新属性更快.

I am not looking for other ways to achieve the same thing. I chose this way, because it proved faster than creating a new object and assigning it the two new properties.

推荐答案

这是 TypeScript 的一个众所周知的限制.最最近的问题要求将string类型缩小到<正在迭代的对象的 code>keyof 目前处于打开状态,等待更多反馈.如果你想看到它的实施,请去那里,放一个喜欢"并可选择提供解释您的用例的评论.

This is a well-known limitation of TypeScript. The most recent issue asking to narrow string type to keyof of the object being iterated is presently open and awaits more feedback. Should you want to see it implemented, please go there, put a "like" on the issue and optionally provide a comment explaining your use case.

与此同时,在 for...in 循环之外声明变量的替代方法是类型转换:

In the meantime an alternative to declaring the variable outside the for...in loop is to type cast:

interface Obj {
    a?: string;
    o?: string;
    b?: string;
}

const obj : Obj = {
    a: "John",
    b: "Mary"
};

for(const p in obj) {
  delete obj[<keyof Obj>p];
}

这篇关于在 for ... in 循环中输入推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆