0
0
Typescriptprogramming~5 mins

How TypeScript infers types automatically - Quick Revision & Summary

Choose your learning style9 modes available
Recall & Review
beginner
What is type inference in TypeScript?
Type inference is TypeScript's ability to automatically figure out the type of a variable or expression without you explicitly telling it.
Click to reveal answer
beginner
How does TypeScript infer the type of a variable declared with <code>let x = 5;</code>?
TypeScript sees the value 5 is a number, so it infers the type of x as number.
Click to reveal answer
intermediate
Can TypeScript infer types for function return values? Give an example.
Yes. For example, <code>function add(a: number, b: number) { return a + b; }</code> TypeScript infers the return type as <code>number</code> because <code>a + b</code> is a number.
Click to reveal answer
beginner
What happens if you declare a variable without initializing it, like <code>let y;</code>?
TypeScript infers the type as any because it has no information about what type y should be.
Click to reveal answer
intermediate
How does TypeScript infer types in arrays? Example with <code>const nums = [1, 2, 3];</code>
TypeScript looks at the elements and infers the array type as number[] because all elements are numbers.
Click to reveal answer
What type does TypeScript infer for let name = "Alice";?
Aboolean
Bnumber
Cany
Dstring
If you write let data; without assigning a value, what type does TypeScript infer?
Aany
Bstring
Cundefined
Dnever
What is the inferred return type of this function?<br>
function greet() { return "Hi"; }
Astring
Bvoid
Cany
Dnumber
Given const flags = [true, false, true];, what type does TypeScript infer for flags?
Anumber[]
Bboolean[]
Cstring[]
Dany[]
Which of these is NOT a benefit of type inference in TypeScript?
ALess need to write explicit types
BCatch errors early
CCode runs faster at runtime
DBetter code readability
Explain how TypeScript infers the type of a variable when you assign a value to it.
Think about how TypeScript guesses the type from the value you give.
You got /3 concepts.
    Describe what happens when you declare a variable without initializing it in TypeScript.
    What does TypeScript do when it has no clues about the variable's type?
    You got /3 concepts.