JavaScript TypeScript Basics 2 — Questions and Answers
Question 1: What does the `readonly` modifier do to a property in TypeScript?
- Makes the property optional
- Prevents the property from being reassigned after initialization (Correct answer)
- Makes the property private to the class
- Marks the property as deprecated
Correct answer: Prevents the property from being reassigned after initialization
The `readonly` modifier prevents a property from being reassigned after it is set during initialization or in the constructor.
Question 2: Which TypeScript utility type makes all properties of a type optional?
- Required<T>
- Readonly<T>
- Partial<T> (Correct answer)
- Pick<T, K>
Correct answer: Partial<T>
`Partial<T>` constructs a type with all properties of T set to optional.
Question 3: What is a TypeScript `enum` used for?
- Defining a set of named numeric or string constants (Correct answer)
- Creating a list of optional parameters
- Declaring a generic type constraint
- Defining a function overload
Correct answer: Defining a set of named numeric or string constants
Enums allow you to define a set of named constants, making intent clearer and reducing magic values.
Question 4: What does the `keyof` operator return in TypeScript?
- The values of all properties of a type
- A union type of all property names of a given type (Correct answer)
- An array of keys at runtime
- The constructor of a type
Correct answer: A union type of all property names of a given type
`keyof T` produces a union type of all the keys (property names) of type T.
Question 5: How do you declare a variable that can be either a `string` or `null` in TypeScript?
- let x: string | null; (Correct answer)
- let x: string? = null;
- let x: maybe<string>;
- let x: string = null;
Correct answer: let x: string | null;
The union type `string | null` correctly allows a variable to hold either a string or null.
Question 6: What is the purpose of the `as` keyword in TypeScript?
- Imports a module alias
- Performs a type assertion to override the inferred type (Correct answer)
- Creates a type alias
- Declares an abstract method
Correct answer: Performs a type assertion to override the inferred type
The `as` keyword is used for type assertion, telling the compiler to treat a value as a specific type.
Question 7: Which of the following correctly defines a tuple type in TypeScript?
- let t: Array<string, number>;
- let t: [string, number]; (Correct answer)
- let t: (string, number)[];
- let t: Tuple<string, number>;
Correct answer: let t: [string, number];
A TypeScript tuple is declared using square brackets with ordered type entries, e.g., `[string, number]`.
What does the `readonly` modifier do to a property in TypeScript?