0
0
Typescriptprogramming~5 mins

Why generics are needed in Typescript - Quick Recap

Choose your learning style9 modes available
Recall & Review
beginner
What problem do generics solve in TypeScript?
Generics let you write flexible and reusable code that works with many types instead of just one specific type.
Click to reveal answer
beginner
How do generics improve code safety?
Generics keep type information so TypeScript can check your code for mistakes before running it.
Click to reveal answer
beginner
What is a simple example of a generic function?
A function that returns the same value it receives, but works with any type, like function identity<T>(arg: T): T { return arg; }.
Click to reveal answer
intermediate
Why not just use any instead of generics?
any disables type checking and can cause bugs. Generics keep type info while still being flexible.
Click to reveal answer
beginner
How do generics help with code reuse?
You write one function or class that works with many types, so you don’t repeat similar code for each type.
Click to reveal answer
What is the main benefit of using generics in TypeScript?
AWrite flexible code that works with many types
BMake code run faster
CAvoid using functions
DDisable type checking
Which keyword is used to declare a generic type in a function?
Afunction
Bclass
CT
Dany
Why is using any less safe than generics?
AIt disables type checking
BIt makes code slower
CIt requires more code
DIt only works with numbers
What does this generic function do? function identity<T>(arg: T): T { return arg; }
AReturns a number always
BReturns the argument unchanged
CReturns a string always
DThrows an error
Generics help avoid which of the following?
AUsing variables
BUsing functions
CWriting comments
DWriting the same code for different types
Explain in your own words why generics are useful in TypeScript.
Think about how generics let you write one function for many types safely.
You got /4 concepts.
    Describe the difference between using any and generics.
    Consider what happens to type checking in each case.
    You got /4 concepts.