Unit 6 - Practice Quiz
1 What is the primary benefit of using TypeScript over plain JavaScript?
2 Which keyword is used in TypeScript to define a custom type for an object's structure?
3
In TypeScript, what does the type string[] represent?
4
In a TypeScript interface, what does a question mark (?) after a property name signify? For example: { name?: string; }
5
If an API is expected to return a user object or null if the user is not found, what is the correct TypeScript type representation?
6 What is the standard file extension for a TypeScript file?
7 What is the name of the main configuration file for a TypeScript project?
8 What is the correct file extension for a TypeScript file that contains JSX code, commonly used with React?
9 What is the primary purpose of a linter like ESLint in a codebase?
10 Static code analysis refers to the process of analyzing source code...
11 Which tool is commonly used alongside a linter to automatically format code and ensure a consistent style across the project?
12 Which browser tool is most commonly used by front-end developers for debugging JavaScript and TypeScript code?
13 What is a 'breakpoint' in the context of debugging?
14 What type of testing focuses on verifying the smallest, individual pieces of code (like a single function) in isolation?
15 Which of the following is a popular JavaScript testing framework often used for testing TypeScript applications?
16
In a test, what is the purpose of an 'assertion' (e.g., expect(result).toBe(5))?
17 What does the 'DRY' principle in software development stand for?
18 What is the process of 'refactoring' code?
19 Why is it important to write clear and meaningful variable names?
20 What is a primary benefit of creating types or interfaces for API responses in a frontend application?
21 You are designing a data model for a user profile that will be used by different parts of an application. You anticipate that a separate 'admin' module might need to add extra properties to this model later. Which TypeScript feature should you primarily use to define the base user profile to allow for this future extensibility via declaration merging?
interface.
type alias with a union.
type alias.
class with private properties.
22
Given the following user data model, which utility type would you use to create a new type UserPreview that includes only the id and name properties?
typescript
interface User {
id: string;
name: string;
email: string;
createdAt: Date;
}
Omit<User, 'email' | 'createdAt'>
Partial<User>
Pick<User, 'id' | 'name'>
Omit and Pick could achieve this.
23
You are modeling the state of an API request which can be 'loading', 'success', or 'error'. What is the key element that makes the following type a 'discriminated union', allowing TypeScript to narrow the type correctly in a switch statement?
typescript
type ApiState =
| { status: 'loading' }
| { status: 'success', data: string[] }
| { status: 'error', error: Error };
type keyword.
data property in one state and an error property in another.
| operator combining different object shapes.
status property having a literal type ('loading', 'success', 'error') that is common to all members of the union.
24
In a React and TypeScript project, you need to type the props for a generic Button component. The component should accept all standard button attributes (like onClick, disabled, etc.) in addition to a custom variant prop. What is the most effective way to type ButtonProps?
interface ButtonProps extends HTMLButtonElement {
variant: 'primary' | 'secondary';
}
type ButtonProps = {
variant: 'primary' | 'secondary';
onClick: () => void;
disabled?: boolean;
// ...manually add all other button props
};
type ButtonProps = {
variant: 'primary' | 'secondary';
} & React.ComponentProps<'button'>;
type ButtonProps = {
variant: 'primary' | 'secondary';
props: React.ComponentProps<'button'>;
};
25
You are creating a generic function fetchData to handle API requests. The function should accept a URL and return a promise that resolves to the data, correctly typed. Which function signature best achieves this?
async function fetchData<T>(url: string): T { ... }
async function fetchData<T>(url: string): Promise<T> { ... }
async function fetchData<T>(url: string): Promise<any> { ... }
async function fetchData(url: string, type: T): Promise<T> { ... }
26
You are setting up a new TypeScript project and want to enforce the strictest type-checking rules to catch as many potential errors as possible at compile time. Which single option in tsconfig.json is the most effective way to enable a wide range of strict checking options, including noImplicitAny and strictNullChecks?
"compilerOptions": { "noImplicitAny": true }
"compilerOptions": { "alwaysStrict": true }
"compilerOptions": { "strict": true }
"compilerOptions": { "strictNullChecks": true }
27
What is the primary reason for using a linter like ESLint alongside the TypeScript compiler (tsc) in a project?
28
When debugging a TypeScript application in the browser's developer tools, you see that your code is executing in a minified JavaScript file, making it unreadable. What is the role of source maps (.map files) in solving this problem?
.ts files.
29 When writing a unit test for a React component that fetches data from an API on mount, why is it essential to mock the API call?
30
Consider the following TypeScript code. What is the primary advantage of using the satisfies operator in this context?
typescript
type Theme = { colors: Record<string, string> };
const myTheme = {
colors: {
primary: '#007bff',
secondary: '#6c757d'
},
spacing: [4, 8, 12] // extra property
} satisfies Theme;
const primaryColor = myTheme.colors.primary; // works
const mainSpacing = myTheme.spacing[0]; // works
myTheme as Theme.
myTheme's structure is assignable to Theme while preserving the inferred, more specific type of myTheme itself.
myTheme to have only the properties defined in Theme, throwing an error on spacing.
spacing array into a string to match the Record<string, string> type.
31
You are adding a JavaScript library to your TypeScript project, but the library does not provide its own type definitions. When you try to import it, TypeScript throws an error: Could not find a declaration file for module 'some-js-library'. What is the standard procedure to resolve this?
@types/some-js-library.
.d.ts file and declare the module with a basic type, like declare module 'some-js-library';
"noImplicitAny": false in tsconfig.json to ignore the error.
32
Why is it necessary to configure ESLint with a custom parser like @typescript-eslint/parser to lint TypeScript code?
tsc) to get type information.
33
You are typing an API response for a product, where the discount field is optional and can be either a number or null. Which TypeScript type definition correctly models this?
typescript
interface Product {
id: number;
name: string;
price: number;
// ... how to type discount?
}
discount: number | null;
discount: number?;
discount?: number;
discount?: number | null;
34 How does using TypeScript in your project enhance the quality and reliability of your tests, particularly when creating mock data?
User, Product) to type your mock data, preventing tests from passing with invalid data shapes that would cause runtime errors.
35
A common JavaScript runtime error is TypeError: Cannot read properties of undefined. How does enabling strictNullChecks in TypeScript's tsconfig.json help mitigate this class of error?
try...catch blocks around your code to handle the error at runtime.
undefined from ever occurring.
null or undefined before you can access its properties, flagging potential errors at compile time.
null or undefined values to empty strings during transpilation.
36 A React component is responsible for fetching user data, managing loading/error states, and rendering the user's profile. According to the Single Responsibility Principle (SRP), what would be the most effective refactoring to improve its maintainability?
.css file.
isLoadingOrError.
useUserData), leaving the component responsible only for rendering the UI based on the hook's output.
37 You are tasked with verifying that a user login form, a password reset modal, and the main navigation bar all work together correctly after a user successfully logs in. Which type of testing is most appropriate for this scenario?
38
In a React component, you have an input element and need to correctly type its onChange event handler. Which type should be used for the event parameter to get proper type-safety and autocompletion for properties like event.target.value?
typescript
const handleChange = (event: ???) => {
console.log(event.target.value);
}
return <input onChange={handleChange} />;
React.ChangeEvent<HTMLInputElement>
any
Event
React.MouseEvent<HTMLInputElement>
39 When using a modern build tool like Vite, how is the TypeScript-to-JavaScript transformation process typically handled during development?
.ts files into one large .js file and then serves it to the browser.
tsc --watch in a separate terminal to handle all transformations.
tsc) on the entire project before starting the dev server, checking for both type errors and syntax.
40 You need to define a type for an object where you know all the values will be numbers, but you don't know the keys in advance (e.g., a dictionary of feature flags). Which TypeScript feature is best suited for this?
Record<string, number>.
class with a getter method.
enum with numeric values.
Map<string, number>.
41
Consider the following TypeScript type utility. What will the type Result resolve to?
typescript
type UnpackPromise<T> = T extends Promise<infer U> ? U : T;
type Func = (id: number) => Promise<{ user: string }>;
type Result = UnpackPromise<ReturnType<Func>>;
42
You are creating a generic React Higher-Order Component (HOC) withData that fetches data and injects it as a prop. Which of the following signatures for withData is the most type-safe and flexible, correctly preserving the original component's props and handling generics?
typescript
// Base component props
interface BaseProps { name: string; }
// Injected prop
interface InjectedProps { data: string[]; }
function withData<P extends object>(
WrappedComponent: React.ComponentType<P & InjectedProps>
): React.FC<P> {
// ... implementation
}
function withData<P>(
WrappedComponent: React.ComponentType<any>
): React.FC<P> {
// ... implementation
}
function withData<P extends InjectedProps>(
WrappedComponent: React.ComponentType<P>
): React.FC<Omit<P, keyof InjectedProps>> {
// ... implementation
}
function withData<P>(
WrappedComponent: React.ComponentType<P>
): React.FC<Omit<P, keyof InjectedProps>> {
// ... implementation
}
43
Given the following mapped type with key remapping, what is the structure of ListenerSet?
typescript
interface Events {
login: { userId: string };
logout: { reason: string };
}
type ListenerSet = {
[E in keyof Events as on${Capitalize<E>}]: (payload: Events[E]) => void;
};
{
onLogin: (payload: { userId: string }) => void;
onLogout: (payload: { reason:string }) => void;
}
{
login: (payload: { userId: string }) => void;
logout: (payload: { reason:string }) => void;
}
{
onLOGIN: (payload: { userId: string }) => void;
onLOGOUT: (payload: { reason:string }) => void;
}
as keyword.
44
You are working in a large monorepo with project references. The shared-logic package is not being recompiled when you build the webapp, even after making changes to it. What is the most likely cause of this issue in the tsconfig.json files?
packages/webapp/tsconfig.json
{
"compilerOptions": { / ... / },
"references": [
{ "path": "../shared-logic" }
]
}
packages/shared-logic/tsconfig.json
{
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"outDir": "dist"
}
}
shared-logic tsconfig.json is missing the "composite": true compiler option.
outDir in shared-logic should be ../webapp/node_modules/shared-logic.
path in the webapp reference should be an absolute path.
webapp tsconfig.json should use "prepend": true in its reference object.
45
You want to test a user-defined type guard function isUser(obj: any): obj is User. Which testing approach provides the most comprehensive validation of both its runtime behavior and its compile-time type-narrowing effect?
typescript
interface User { id: number; name: string; }
function isUser(obj: any): obj is User {
return obj && typeof obj.id === 'number' && typeof obj.name === 'string';
}
isUser.prototype.constructor.name to be Function.
isUser and asserts the result is true. Then, inside an if (isUser(obj)) block, access obj.name to ensure the test itself compiles.
User interface and use jest.isMockFunction to verify isUser was called.
isUser(validUser) is true, and another that asserts isUser(invalidObject) is false.
46
A class hierarchy violates the Liskov Substitution Principle (LSP). Given the base class Rectangle, which Square subclass implementation is the primary offender?
typescript
class Rectangle {
protected width: number = 0;
protected height: number = 0;
setWidth(value: number) { this.width = value; }
setHeight(value: number) { this.height = value; }
getArea(): number { return this.width * this.height; }
}
class Square extends Rectangle {
setWidth(value: number) {
this.width = value;
this.height = value;
}
setHeight(value: number) {
this.width = value;
this.height = value;
}
}
class Square extends Rectangle {
constructor(size: number) {
super();
this.width = size;
this.height = size;
}
}
class Square extends Rectangle {
setWidth(value: number | string) { // Widens input type
const numValue = Number(value);
this.width = numValue;
this.height = numValue;
}
// ... setHeight is similar
}
class Square extends Rectangle {
getArea(): number {
// A square's area is side side
return this.width this.width;
}
}
47
Your project uses typescript-eslint and you have a function that intentionally doesn't return a value from a promise chain inside an event listener. This triggers the @typescript-eslint/no-floating-promises rule. What is the most idiomatic and safe way to handle this specific case without disabling the rule globally?
typescript
button.addEventListener('click', () => {
// This promise is intentionally not awaited.
doSomethingAsync(); // ESLint: Promise returned from function is ignored.
});
void operator: void doSomethingAsync();
// eslint-disable-next-line @typescript-eslint/no-floating-promises comment.
(async () => { await doSomethingAsync(); })();
const _ = doSomethingAsync();
48 You are debugging a minified production build of a React application with source maps. In the browser's developer tools, you place a breakpoint inside a component, but the debugger pauses on a seemingly unrelated line in a different component. What is the most probable cause for this source map misalignment?
.js.map files with the correct Content-Type header.
tsconfig.json has "sourceMap": false which overrides the bundler's configuration.
49
You have a discriminated union to model the state of an API request. Why does the following React component code fail to compile?
typescript
type ApiState<T> =
| { status: 'loading' }
| { status: 'success', data: T }
| { status: 'error', error: Error };
function MyComponent<T>({ state }: { state: ApiState<T> }) {
if (state.status === 'success') {
// Long running computation...
// ... more code
}
if (state.status === 'success') {
// ERROR: Property 'data' does not exist on type 'ApiState<T>'.
// Property 'data' does not exist on type '{ status: "loading"; }'.
return <div>{state.data}</div>;
}
return null;
}
switch statement for the type guard to be effective.
in operator to check for the data property before accessing it.
T has not been constrained with extends object.
if statements for union types.
50
You want to add a currentUser property to the Request object of the Express.js framework across your entire project. What is the correct way to do this using declaration merging in a file like src/types/express.d.ts?
import 'express';
interface Request {
currentUser?: MyUserType;
}
// This should be at the top level of a module
import { Request } from 'express';
Request.prototype.currentUser = undefined;
// In a regular .ts file, not a .d.ts file
import { Request } from 'express';
declare module 'express' {
interface Request {
currentUser?: MyUserType;
}
}
declare namespace Express {
export interface Request {
currentUser?: MyUserType;
}
}
51
A function in your TypeScript code relies on a generic type T to perform a validation check at runtime. The initial attempt fails. Why does isValidType always return false, and what is the idiomatic way to fix it?
typescript
class User {}
function createAndValidate<T>(data: any): T | null {
const instance = new T(data); // Assume T has a constructor
if (instance instanceof T) { // <-- Problematic line
return instance;
}
return null;
}
T must be T extends new (...args: any[]) => any for instanceof to work.
T is a type and is erased at runtime; it cannot be used as a value in an instanceof check. The fix is to pass the class constructor as an argument.
instanceof operator does not work with generic types. It should be replaced with typeof instance === 'T'.
new T(data) call is what's failing, and that needs to be wrapped in a try...catch block.
52
What is the resulting type of DeepReadonly<APIResponse> given the following recursive mapped type?
typescript
type DeepReadonly<T> = {
readonly [P in keyof T]: T[P] extends Function
? T[P]
: T[P] extends object
? DeepReadonly<T[P]>
: T[P];
};
interface APIResponse {
id: number;
user: {
name: string;
address: {
street: string;
};
};
getData: () => string;
}
getData method will become readonly and cannot be reassigned.
{
readonly id: number;
readonly user: {
readonly name: string;
readonly address: {
readonly street: string;
};
};
readonly getData: () => string;
}
id, user, and getData are readonly.
53
You are mocking a module that exports a class using jest.mock. How do you correctly type the mocked class to ensure that its methods are Jest.Mock instances, allowing you to inspect calls like mock.calls?
typescript
// service.ts
export class ApiService {
fetchData(id: string): Promise<string> { / ... / }
}
// service.test.ts
import { ApiService } from './service';
jest.mock('./service');
// What type should MockedApiService have?
const MockedApiService = ApiService as ???;
// Test code...
const instance = new MockedApiService();
instance.fetchData('123');
any
typeof ApiService
{ new(): { fetchData: jest.Mock } }
jest.Mocked<typeof ApiService>
54
You are refactoring a legacy function from using any to being type-safe. The function accesses a property from an object, where the property key is dynamic. The object can be one of several types in a union. Why does the refactored getProperty function fail to compile in this scenario?
typescript
interface User { name: string; }
interface Product { price: number; }
type Model = User | Product;
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
function logValue(model: Model, key: string) {
// Assume key is 'name' or 'price'
// ERROR on the next line!
const value = getProperty(model, key as keyof Model);
console.log(value);
}
key exists on all constituents of the union type Model. For example, price is not a key of User.
key as keyof Model is incorrect; it should be key as 'name' | 'price'.
getProperty cannot handle union types for its first argument obj.
logValue function needs to use a type guard to narrow model to either User or Product before calling getProperty.
55
In a project using both tsc and eslint with @typescript-eslint/parser, you notice that npx tsc --noEmit reports zero errors, but npx eslint . reports a type-related error, such as a violation of @typescript-eslint/no-unsafe-assignment. What is the most likely configuration issue causing this discrepancy?
.eslintrc file is missing "parser": "@typescript-eslint/parser".
eslint-plugin-typescript is deprecated and should be @typescript-eslint/eslint-plugin.
tsc and the one running eslint.
tsconfig.json file (or no file at all) than the one tsc is using, leading to a different understanding of the project's type information.
56
Using TypeScript's Variadic Tuple Types, you want to create a type Curry that transforms a function's parameter list into a series of nested functions. Which implementation correctly defines Curry?
typescript
// Desired outcome:
// type F = (a: string, b: number, c: boolean) => void;
// type CurriedF = Curry<F>;
// CurriedF should be: (a: string) => (b: number) => (c: boolean) => void;
type Curry<F> =
F extends (arg: infer A, ...rest: infer R) => infer RT
? R extends []
? (arg: A) => RT
: (arg: A) => Curry<(...args: R) => RT>
: never;
type Curry<F extends (...args: any) => any> = (arg: Parameters<F>[0]) => ReturnType<F>;
type Curry<A extends any[], R> = (head: A[0], ...tail: A) => Curry<typeof tail, R>;
type Curry<F> = F extends (...args: infer A) => infer R ? A extends [infer H, ...infer T] ? (arg: H) => Curry<(...args: T) => R> : R : never;
57
You are designing a polymorphic React component <Box as={...}> that can render as different HTML elements. Which type definition for the Box component's props is most accurate and powerful, allowing for type-safe inference of the underlying element's attributes?
typescript
import React from 'react';
type BoxProps<C extends React.ElementType> = {
as?: C;
children: React.ReactNode;
} & React.ComponentPropsWithoutRef<C>;
function Box<C extends React.ElementType = 'div'>({ as, ...props }: BoxProps<C>) {
const Component = as || 'div';
return <Component {...props} />;
}
// Usage:
// <Box as="a" href="/home">Home</Box> <-- href should be allowed
// <Box as="button" onClick={() => {}}>Click</Box> <-- onClick should be allowed
// <Box as="div" href="/home">Home</Box> <-- href should be an error
What is the primary role of React.ComponentPropsWithoutRef<C> in this pattern?
C, excluding ref, allowing attributes like href for <a> or onClick for <button> to be type-checked.
C with the props of a base <div> element for default attributes.
as prop itself is one of the valid HTML tags like 'div', 'a', or 'span'.
children and className from the component type C.
58
What is the primary benefit of using a TypeScript enum for defining a set of constants over a simple as const object literal, specifically in the context of ensuring nominal typing rather than structural typing?
typescript
// Option A: Enum
enum UserRole {
ADMIN = 'ADMIN',
EDITOR = 'EDITOR'
}
// Option B: Object with 'as const'
const UserRoleObj = {
ADMIN: 'ADMIN',
EDITOR: 'EDITOR'
} as const;
type UserRoleObjType = typeof UserRoleObj[keyof typeof UserRoleObj];
enum members are transpiled into more performant JavaScript code than object lookups.
enum creates a distinct, nominal type. A function fn(role: UserRole) cannot be accidentally called with a string 'ADMIN', even though its value is the same. UserRoleObjType is just a string literal union ('ADMIN' | 'EDITOR') and offers no such protection.
as const objects cannot be iterated over at runtime, whereas enums can.
enum can have computed members, while an as const object's values must be literals.
59
You are migrating a large JavaScript project to TypeScript and want to enable allowJs and checkJs in your tsconfig.json to type-check JS files using JSDoc comments. Why might the TypeScript compiler fail to infer the type of a function parameter in a .js file, even with a seemingly correct JSDoc comment?
javascript
// file.js
/*
@param {import('./types').User} user - The user object.
*/
export function getUserName(user) {
return user.name; // TS Error: Property 'name' does not exist on type '{...}'.
}
// types.ts
export interface User { name: string; }
@type instead of @param for imports.
User type is an interface, which cannot be referenced from JSDoc in .js files; it must be a type alias or a class.
import('./types').User syntax requires moduleResolution to be set to nodenext or node16 in tsconfig.json for JSDoc.
@param tag requires the name of the parameter, so it should be /** @param {import('./types').User} user */.
60
You are writing a unit test for a generic utility function. Which assertion strategy is most effective at ensuring the function's type-level correctness for a variety of inputs?
typescript
function pluck<T, K extends keyof T>(items: T[], key: K): T[K][] {
return items.map(item => item[key]);
}
it blocks, each with a different concrete type (e.g., pluck(users, 'name'), pluck(products, 'price')) and assert the runtime values.
jest.fn() to mock the pluck function and test its call signatures.
as any to avoid type errors in tests and only focus on the runtime logic.
tsd or expect-type to write compile-time assertions that check the inferred return type of the function, in addition to runtime expect calls.