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?
✗ Incorrect
TypeScript looks at the argument's type to decide what the generic type should be.
If a function has two generic types
T and U, how does TypeScript infer them?✗ Incorrect
TypeScript infers each generic type from the matching argument's type.
What should you do if TypeScript cannot infer a generic type?
✗ Incorrect
You provide the type explicitly to help TypeScript understand what you mean.
Which of these is a benefit of TypeScript's generic type inference?
✗ Incorrect
Inference helps keep code clean without losing type safety.
Given
function wrap<T>(value: T): { value: T }, what is the inferred type of T when calling wrap('hello')?✗ Incorrect
Since 'hello' is a string, TypeScript infers
T as string.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.