问题标签 [type-annotation]
For questions regarding programming in ECMAScript (JavaScript/JS) and its various dialects/implementations (excluding ActionScript). Note JavaScript is NOT the same as Java! Please include all relevant tags on your question; e.g., [node.js], [jquery], [json], [reactjs], [angular], [ember.js], [vue.js], [typescript], [svelte], etc.
typescript - Typescript - 将变量声明为扩展接口的类型
假设我有一个名为MyIFace
. 有没有办法声明一个使用类型注释扩展该接口的类型的成员属性?我尝试发布我正在搜索的伪代码:
这个先前的问题谈到了交集类型,这显然似乎很好(编译器没有抱怨),但最终它不是我需要的。事实上,声明x: any & MyIFace;
并不像我需要的结构:它声明 x 具有any和MyIFace蓝图,而我想声明 x 具有扩展MyIFace蓝图的any的蓝图。
python - 将 TypeVar 上限设置为之后定义的类
我正在查看typeshed
源代码,发现pathlib.pyi
它执行以下操作:
我有一个类似的情况,基类从__new__
(类似于Path
)返回一个子类,因此类型注释也相似。但是,将bound
关键字定义为下面定义的类会解析为NameError,因为名称尚未解析(正如我所预料的那样;由于typeshed
来源而尝试)。
如何typeshed
摆脱这个?这对我的打字来说是完美的,否则我必须这样做:
并且我所有的 linter 警告都满足("expected type _MT, got object instead"
)...
更好的匹配案例是输入工厂方法,因为我使用__new__
的工厂方法类似于Path
它的方式和描述here。不过,很高兴知道如何在不使用字符串的情况下typeshed
完成此前向引用。bound
python - 为没有初始值的变量键入注释
我一直在阅读 PEP484 和 526,但仍然无法弄清楚在没有初始值的情况下对变量进行类型注释的更好方法是什么。
假设您有一个类,并且__init__
您想在其中声明一个变量,但不提供初始值,以便稍后在代码中进行赋值。通常我通常会做的是:
这行得通,但我觉得使用 Optional 会变得__init__
过于忙碌且难以阅读。相反,我能做的是:
显然,这会使变量未初始化,但只要它们在被引用之前被正确分配,一切都会正常工作,并且如果我在__init__
.
使用第二种方法时,未初始化变量是否会出现任何具体问题?
python - 竖线“|”是什么意思 (管道)在函数参数类型注释中是什么意思?
我遇到了这样的签名功能:
这是什么意思?
这是我的 python 3.8 上的语法错误。我是否需要从中导入某些东西future
才能使其工作?
python - How do I annotate a type which has an extra attribute with mypy?
I have an ast.UnaryOp
object, but I manually added a parent
attribute (see answer). How do I annotate this in a function?
I currently simply have:
But mypy complains (rightfully so) that ast.UnaryOp
does not have the parent
attribute.
How can I tell mypy that the node
is not ast.UnaryOp
but ast.UnaryOp + parent attribute
?
My Try
I've created my own UnaryOp
class which has a parent attribute. I can use this for type-casting:
The downside of it is that I need to type cast in a lot of places and that I introduced Any
. I would prefer if I could just state somewhere that all ast.*
types in that file do have a parent
attribute
swift - 关联类型可以有类型注释吗?
我正在关注一个示例,作者在 associatedType 上使用了类型注释,但是 Xcode 抛出错误“无法在范围内找到类型 *”。没有使用任何 Cocoapods 或第三方框架。我也尝试构建该项目,但无法编译。
这是单独的 Swift 文件中的类型:
这是另一个 Swift 文件中的代码,它的 associatedType 试图使用类型注释:
为什么第二个 Swift 文件看不到数据类型以便编译?
python - 为什么此代码会生成类型注释警告?
我有带有这些类型注释的 python 函数
为什么下面的代码在我调用 func_2 的那一行给出警告“预期类型列表 [str,Any]' 得到 'str'”?
这是否意味着我的类型检查器有问题,或者我的代码有问题?
python - pyright:在具有最小值/最大值的同质列表中使用 TypeVar
我试图了解如何使用TypeVar
pyright。
我构建了以下小功能:
它使 pyright 在线抱怨:
因为:
“min”的重载与提供的参数不匹配
参数类型:(TypedList[int], TypedList[int])
[版权:reportGeneralTypeIssues]
此外,它还抱怨:
因为:
预期的类类型,但收到“int”
和:
非法类型注释:除非是类型别名,否则不允许使用变量
mypy 似乎在这条线上工作得很好。关于问题是什么以及如何解决问题的任何想法?
谢谢!