0
0
Typescriptprogramming~5 mins

Generic function syntax in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a generic function in TypeScript?
A generic function is a function that can work with any data type, allowing you to write flexible and reusable code by using type variables.
Click to reveal answer
beginner
How do you declare a generic function in TypeScript?
You declare a generic function by adding a type parameter inside angle brackets <T> before the function's parameters, like: <br>function example<T>(arg: T): T { return arg; }
Click to reveal answer
beginner
What does the <T> mean in a generic function?
The <T> is a placeholder for a type that will be specified when the function is called. It stands for 'Type' and can be replaced with any type like number, string, or a custom type.
Click to reveal answer
intermediate
Can a generic function have multiple type parameters? Give an example.
Yes, a generic function can have multiple type parameters separated by commas, like:<br>function pair(first: T, second: U): [T, U] { return [first, second]; }
Click to reveal answer
intermediate
Why use generic functions instead of using 'any' type?
Generic functions keep type safety by preserving the type information, while 'any' disables type checking and can lead to errors. Generics help catch mistakes during coding.
Click to reveal answer
What does the <T> represent in a TypeScript generic function?
AA placeholder for a type to be specified later
BA variable name
CA function name
DA keyword to declare a constant
How do you declare a generic function that returns the same type as its argument?
Afunction example(arg: number): number { return arg; }
Bfunction example(arg: any): any { return arg; }
Cfunction example<T>(arg: T): T { return arg; }
Dfunction example<T>(arg: number): T { return arg; }
Can a generic function have more than one type parameter?
AYes, separated by commas inside <>
BNo, only one type parameter is allowed
CYes, but only if they are the same type
DNo, you must use multiple functions instead
What is the main advantage of using generic functions over 'any' type?
AThey use less memory
BThey run faster
CThey allow any value without restrictions
DThey keep type safety and help catch errors
Which of the following is a valid generic function syntax in TypeScript?
Afunction identity(arg: T): T { return arg; }
Bfunction identity<T>(arg: T): T { return arg; }
Cfunction identity<T>(arg): T { return arg; }
Dfunction identity(arg): arg { return arg; }
Explain how to write a generic function in TypeScript and why it is useful.
Think about how you can make a function work with different types without repeating code.
You got /4 concepts.
    Describe the difference between using a generic type parameter and the 'any' type in a function.
    Consider how TypeScript helps you avoid mistakes.
    You got /4 concepts.