0
0
Typescriptprogramming~5 mins

How TypeScript infers generic types - Quick Revision & Summary

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean when TypeScript 'infers' generic types?
TypeScript automatically figures out the specific types to use for generic parameters based on the values you provide when calling a function or creating an object.
Click to reveal answer
beginner
How does TypeScript infer the generic type in this function?<br>
function identity<T>(arg: T): T { return arg; }
TypeScript looks at the argument you pass to identity and sets T to that argument's type automatically. For example, if you call identity(5), T becomes number.
Click to reveal answer
intermediate
Can TypeScript infer multiple generic types in a function? Give an example.
Yes. For example:<br>
function pair(first: T, second: U): [T, U] { return [first, second]; }
When you call pair('hello', 10), TypeScript infers T as string and U as number.
Click to reveal answer
beginner
What happens if TypeScript cannot infer a generic type?
You must explicitly provide the generic type when calling the function or creating the object. For example, identity<string>('text') tells TypeScript exactly what type to use.
Click to reveal answer
beginner
Why is generic type inference helpful in TypeScript?
It saves you from writing extra type annotations, making code cleaner and easier to read, while still keeping type safety.
Click to reveal answer
What does TypeScript use to infer a generic type in a function?
AThe type of the argument passed to the function
BThe return type of the function
CThe name of the generic parameter
DThe order of the generic parameters
If a function has two generic types T and U, how does TypeScript infer them?
AFrom the first argument only
BFrom the function's return type
CFrom the types of the corresponding arguments passed
DIt cannot infer multiple generic types
What should you do if TypeScript cannot infer a generic type?
AExplicitly specify the generic type when calling the function
BRename the generic type
CIgnore the error and run the code
DRemove the generic type
Which of these is a benefit of TypeScript's generic type inference?
AIt disables type checking
BIt removes type safety
CIt makes code longer
DIt reduces the need for extra type annotations
Given function wrap<T>(value: T): { value: T }, what is the inferred type of T when calling wrap('hello')?
Anumber
Bstring
Cboolean
Dany
Explain how TypeScript infers generic types when you call a generic function.
Think about how TypeScript guesses the types based on what you pass in.
You got /3 concepts.
    Describe a situation where you need to explicitly specify generic types in TypeScript.
    Consider functions with no input or complex types.
    You got /3 concepts.