Type parameter

3 snippets across 2 stacks — Python, TypeScript

Also written as parameter types

PYPython

Type Hints for Functions

PY · Functions
syntax
def func(param: Type) -> ReturnType:
example
from collections.abc import Callable

def apply(
    values: list[int],
    transform: Callable[[int], int]
) -> list[int]:
    return [transform(v) for v in values]

result = apply([1, 2, 3], lambda x: x * 10)
print(result)
output
[10, 20, 30]

Note Use collections.abc.Callable for function type hints. The format is Callable[[ArgTypes], ReturnType]. For complex signatures, consider typing.Protocol.

Type Parameter Syntax (3.12+)

PY · Modern Features
syntax
def func[T](arg: T) -> T: ...
class Name[T]: ...
example
# New syntax (3.12+) - no more TypeVar boilerplate
def first_element[T](items: list[T]) -> T:
    return items[0]

print(first_element([10, 20, 30]))
print(first_element(["a", "b"]))

# Generic class
class Pair[A, B]:
    def __init__(self, left: A, right: B):
        self.left = left
        self.right = right

p = Pair("name", 42)
print(p.left, p.right)
output
10
a
name 42

Note The [T] syntax on def/class replaces manual TypeVar declarations. It is scoped to the function or class, unlike module-level TypeVar which could be reused accidentally.

TSTypeScript

Generic Functions

TS · Generics
syntax
function fn<T>(param: T): T { ... }
const fn = <T>(param: T): T => { ... };
example
function firstElement<T>(items: T[]): T | undefined {
  return items[0];
}

const topScore = firstElement([95, 87, 72]); // number | undefined
const firstName = firstElement(["Alice", "Bob"]); // string | undefined

// Multiple type parameters
function mapEntry<K, V>(key: K, value: V): [K, V] {
  return [key, value];
}
const entry = mapEntry("age", 30); // [string, number]
output
// TypeScript infers T from the argument — no need to specify it manually

Note Type parameters are inferred from arguments in most cases. Only specify them explicitly when inference gives the wrong type. In .tsx files, arrow generics need a trailing comma: <T,>(param: T) to avoid JSX ambiguity.