Annotate variable

2 snippets across 2 stacks - Python, TypeScript

PYPython

Type Hints / Annotations

PY · Variables & Types
Syntax
name: type = value
Example
price: float = 19.99
items: list[str] = ["apple", "bread"]
user_map: dict[str, int] = {"alice": 1}
Output
# No runtime enforcement - hints are for tools and readers

Note Type hints do not prevent wrong types at runtime. Use mypy or pyright for static checking. Since 3.12, you can use the new type statement for aliases.

TSTypeScript

Variable Annotations

TS · Type Annotations
Syntax
let varName: Type = value;
const varName: Type = value;
Example
let orderId: string = "ORD-7821";
const maxRetries: number = 3;
let tags: string[] = ["urgent", "billing"];

// Often unnecessary when the type is obvious
let count = 0; // inferred as number
const label = "total"; // inferred as literal "total"
Output
// Explicit annotations override inference when needed

Note Let TypeScript infer when the type is obvious from the initializer. Add explicit annotations when: the inferred type is too wide, you are declaring without initializing, or you want documentation clarity.

Frequently asked questions

How does Python handle annotate variable?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Type Hints / Annotations" snippet in Python uses `name: type = value`.
Which code does the Python example use?
The "Type Hints / Annotations" snippet uses `name: type = value`, from the Variables & Types section of the Python cheat sheet.
Which stacks cover "annotate variable" on this page?
Python, TypeScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Type Hints / Annotations": Type hints do not prevent wrong types at runtime. Use mypy or pyright for static checking. Since 3.12, you can use the new type statement for aliases.