from collections.abcimportCallabledefapply(
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.
# New syntax (3.12+) - no more TypeVar boilerplatedef first_element[T](items:list[T])->T:return items[0]print(first_element([10,20,30]))print(first_element(["a","b"]))# Generic classclassPair[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.
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 | undefinedconst firstName =firstElement(["Alice","Bob"]);// string | undefined// Multiple type parametersfunction 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.
Frequently asked questions
How does Python handle type parameter?
This task is covered in 2 stacks on this page: Python, TypeScript. The "Type Hints for Functions" snippet in Python uses `def func(param: Type) -> ReturnType:`.
Which code does the Python example use?
The "Type Hints for Functions" snippet uses `def func(param: Type) -> ReturnType:`, from the Functions section of the Python cheat sheet.
Which stacks cover "type parameter" on this page?
Python, TypeScript. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Type Hints for Functions": Use collections.abc.Callable for function type hints. The format is Callable[[ArgTypes], ReturnType]. For complex signatures, consider typing.Protocol.