Last modified: Aug 11, 2025 By Alexander Williams
Python Typer Type Hints Usage Guide
Python Typer makes CLI app development easy. Type hints improve code quality and user experience. This guide covers key type hints.
Why Use Type Hints in Typer?
Type hints help validate user input. They auto-generate help texts. They make your code more maintainable.
Typer uses Python's type system. It converts types automatically. It shows errors for invalid input.
Basic Type Hints
int Type Hint
Use int
for numeric inputs. Typer converts strings to integers. It rejects non-numeric values.
import typer
def main(age: int):
typer.echo(f"You are {age} years old")
if __name__ == "__main__":
typer.run(main)
$ python app.py 25
You are 25 years old
$ python app.py abc
Error: Invalid value for 'AGE': 'abc' is not a valid integer
Enum Type Hint
Enums restrict choices. They create dropdowns in help texts. Use them for fixed options.
from enum import Enum
import typer
class Color(str, Enum):
RED = "red"
GREEN = "green"
BLUE = "blue"
def main(color: Color):
typer.echo(f"You chose {color.value}")
if __name__ == "__main__":
typer.run(main)
$ python app.py red
You chose red
$ python app.py yellow
Error: Invalid value for 'COLOR': 'yellow' is not one of 'red', 'green', 'blue'
Advanced Type Hints
Path Type Hint
Path
handles file paths. It checks if files exist. It converts strings to Path objects.
from pathlib import Path
import typer
def main(file: Path):
if file.exists():
typer.echo(f"File size: {file.stat().st_size} bytes")
else:
typer.echo("File not found")
if __name__ == "__main__":
typer.run(main)
$ python app.py data.txt
File size: 1024 bytes
Optional Type Hint
Optional
makes arguments non-required. Combine it with default values. Learn more in our Arguments vs Options guide.
from typing import Optional
import typer
def main(name: Optional[str] = None):
if name:
typer.echo(f"Hello {name}")
else:
typer.echo("Hello stranger")
if __name__ == "__main__":
typer.run(main)
$ python app.py --name Alice
Hello Alice
$ python app.py
Hello stranger
list Type Hint
list
accepts multiple values. Use it for array inputs. It works with other types too.
from typing import List
import typer
def main(numbers: List[int]):
total = sum(numbers)
typer.echo(f"Sum: {total}")
if __name__ == "__main__":
typer.run(main)
$ python app.py 1 2 3
Sum: 6
Combining Type Hints
You can mix type hints. For example, List[Path]
or Optional[Enum]
. This creates powerful validations.
For complex apps, see our Commands guide. It shows how to structure larger projects.
Installation Note
Need Typer? Follow our installation guide. It's quick and easy.
Conclusion
Type hints make Typer apps robust. They improve user experience. They reduce bugs.
Key takeaways: Use int
for numbers, Enum
for choices, Path
for files, Optional
for non-required args, and list
for multiple values.
Start using type hints today. Your future self will thank you.