我的问题与
中的问题相同https://github.com/microsoft/TypeScript/issues/29729
但我无法在 vscode 中使用 Python 和智能感知找到解决方案。
在 test_function 的调用中,我没有获得文字与字符串联合的类型提示。我希望“name1”和“name2”出现在自动完成中。
from typing import Literal, Union, Optional
Name = Union[
Literal[
"name1",
"name2"
],
str]
def test_function(name: Name):
pass
test_function("")
发布了一个解决方法,虽然我不熟悉所使用的打字稿语法,但据我推测,Python 没有与 & 运算符等效的东西。
Name类型和string类型是等价的吗?有什么解决方法吗?我想允许任意名称,但也可以自动完成硬编码名称。
谢谢!
我发现了一些有用的东西,尽管我不确定为什么。如果您在 Union 中使用
AnyStr
而不是 str
,那么 Intellisense 将自动完成您的文字,并且 VScode 不会报告问题..
from typing import Literal, Union, AnyStr
Name = Union[
Literal[
"name1",
"name2"
],
AnyStr
]
def test_function(name: Name):
print(name)
pass
test_function("")