In TypeScript I used to have the following and it will work as type inference:
JavaScript
x
2
1
function func(x: "#1" | "#2" | "#3" = "#2"): void {}
2
The above example should give you options and autocompletion when typing, and error when you type options that are not in the list of options.
When I was exploring Python I found the typing
module. But what I tried didn’t work, and I couldn’t find what I’ve hopped to find.
My expected code:
JavaScript
1
3
1
def func(x: "#1" | "#2" | "#3" = "#2") -> None:
2
pass
3
My expected result should be similar to the one in TypeScript.
Advertisement
Answer
JavaScript
1
16
16
1
from typing import Literal, TypeAlias
2
3
4
Valid: TypeAlias = Literal["#1", "#2", "#3"]
5
6
7
def func(x: Valid = "#2") -> None:
8
print(x)
9
10
11
if __name__ == "__main__":
12
func("#1")
13
func("#2")
14
func("#3")
15
func("#4")
16
All valid, except the last line makes mypy
rightfully complain:
error: Argument 1 to "func" has incompatible type "Literal['#4']"; expected "Literal['#1', '#2', '#3']" [arg-type]
Note that in Python, the interpreter does not care about the type annotations and will execute that last function call without a problem.