Recall & Review
beginner
What is the purpose of specifying parameter types in a constructor in TypeScript?
Specifying parameter types in a constructor helps ensure that the values passed when creating an object are of the expected types, preventing errors and improving code clarity.
Click to reveal answer
beginner
How do you define a constructor with typed parameters in a TypeScript class?
You declare the constructor with parameters followed by a colon and the type, for example:
constructor(name: string, age: number) { ... }Click to reveal answer
intermediate
Can constructor parameters in TypeScript be optional? How?
Yes, by adding a question mark after the parameter name, e.g.,
constructor(name?: string) { ... }, making the parameter optional.Click to reveal answer
beginner
What happens if you pass a wrong type to a constructor parameter in TypeScript?
TypeScript will show a compile-time error, preventing the code from running until the type mismatch is fixed.
Click to reveal answer
intermediate
How can you automatically create and assign class properties from constructor parameters in TypeScript?By adding access modifiers (public, private, protected, readonly) before the constructor parameters, TypeScript creates and assigns properties automatically, e.g.,
constructor(public name: string) { }Click to reveal answer
How do you specify that a constructor parameter 'age' must be a number in TypeScript?
✗ Incorrect
Option A correctly declares 'age' as a number type parameter.
What does adding a question mark after a constructor parameter name do?
✗ Incorrect
A question mark after a parameter name makes it optional.
Which of these will automatically create a class property from a constructor parameter?
✗ Incorrect
Using 'public' before the parameter automatically creates and assigns the property.
What error will TypeScript show if you pass a string to a constructor expecting a number?
✗ Incorrect
TypeScript shows a type error at compile time for type mismatches.
Which syntax correctly defines a constructor with an optional string parameter 'title'?
✗ Incorrect
Option D uses the correct syntax for an optional parameter.
Explain how constructor parameter types improve code safety and readability in TypeScript.
Think about what happens when you pass wrong types to constructors.
You got /4 concepts.
Describe how to use access modifiers in constructor parameters to create class properties automatically.
Focus on the shortcut TypeScript offers inside constructors.
You got /4 concepts.