EN
TypeScript - create generic function type
5 points
In this article, we want to show how to create generic function type in TypeScript.
Quick solution:
xxxxxxxxxx
1
type Func = <T> (arg: T) => void; // type that provides generic function
2
3
// OR:
4
5
type Func<T> = (arg: T) => void; // generic type that generates function
Note: to know how to create generic function check this article.
Type that provides generic function:
xxxxxxxxxx
1
type Func = <T extends unknown> (arg: T) => void; // OR: type Func = <T> (arg: T) => void;
2
3
4
// Usage example:
5
6
const print: Func = <T extends unknown> (arg: T): void => { console.log(arg); };
7
8
print(true); // true
9
print(3.14); // 3.14
10
print('Hi there!'); // Hi there!
Note:
print()
is generic function, so we can use it with different arguments.
Generic type that generates functions:
xxxxxxxxxx
1
type Func<T extends unknown> = (arg: T) => void; // OR: type Func<T> = (arg: T) => void;
2
3
4
// Usage example:
5
6
const print1: Func<boolean> = (arg: boolean): void => { console.log(arg); };
7
const print2: Func<number> = (arg: number): void => { console.log(arg); };
8
const print3: Func<string> = (arg: string): void => { console.log(arg); };
9
10
print1(true); // true
11
print2(3.14); // 3.14
12
print3('Hi there!'); // Hi there!
Note:
Func<>
is generic type, so it generates functions that have specific argument types.