Unit 6 - Practice Quiz

INT219 60 Questions
0 Correct 0 Wrong 60 Left
0/60

1 What is the primary benefit of using TypeScript over plain JavaScript?

Type-safe data models Easy
A. It adds static type-checking to prevent common errors.
B. It makes web pages load faster.
C. It is a completely different language from JavaScript.
D. It automatically styles web components.

2 Which keyword is used in TypeScript to define a custom type for an object's structure?

Type-safe data models Easy
A. model
B. interface
C. struct
D. object

3 In TypeScript, what does the type string[] represent?

Type-safe data models Easy
A. An array where every element is a string
B. A single string
C. A function that returns a string
D. An object with string properties

4 In a TypeScript interface, what does a question mark (?) after a property name signify? For example: { name?: string; }

Component and API typing strategies Easy
A. The property is optional.
B. The property is required.
C. The property is private and cannot be accessed.
D. The property can be of any type.

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?

Component and API typing strategies Easy
A. User & null
B. User
C. User | null
D. User[]

6 What is the standard file extension for a TypeScript file?

Integration of TypeScript in frontend projects Easy
A. .js
B. .type
C. .tsc
D. .ts

7 What is the name of the main configuration file for a TypeScript project?

Integration of TypeScript in frontend projects Easy
A. tsconfig.json
B. webpack.config.js
C. typescript.config
D. package.json

8 What is the correct file extension for a TypeScript file that contains JSX code, commonly used with React?

Integration of TypeScript in frontend projects Easy
A. .ts-react
B. .jsx
C. .rts
D. .tsx

9 What is the primary purpose of a linter like ESLint in a codebase?

Static code analysis Easy
A. To automatically find and report potential errors and style issues in the code.
B. To run the application in a browser.
C. To compile the code into a single file.
D. To manage project dependencies.

10 Static code analysis refers to the process of analyzing source code...

Static code analysis Easy
A. ...by multiple users simultaneously.
B. ...while it is being executed.
C. ...after it has been deployed.
D. ...without executing it.

11 Which tool is commonly used alongside a linter to automatically format code and ensure a consistent style across the project?

Static code analysis Easy
A. Jest
B. Webpack
C. Node.js
D. Prettier

12 Which browser tool is most commonly used by front-end developers for debugging JavaScript and TypeScript code?

Debugging workflows Easy
A. The browser's settings page
B. The search bar
C. The Developer Tools (or DevTools)
D. The bookmarks manager

13 What is a 'breakpoint' in the context of debugging?

Debugging workflows Easy
A. An error message displayed to the user.
B. A point where the application has crashed.
C. A specific point in the code where the debugger will intentionally pause execution.
D. A comment in the code explaining a bug.

14 What type of testing focuses on verifying the smallest, individual pieces of code (like a single function) in isolation?

Testing fundamentals Easy
A. End-to-End Testing
B. User Acceptance Testing
C. Unit Testing
D. Integration Testing

15 Which of the following is a popular JavaScript testing framework often used for testing TypeScript applications?

Testing fundamentals Easy
A. Jest
B. Bootstrap
C. Angular
D. jQuery

16 In a test, what is the purpose of an 'assertion' (e.g., expect(result).toBe(5))?

Testing fundamentals Easy
A. To check if an actual value meets an expected condition.
B. To set up the initial state for the test.
C. To clean up resources after the test is complete.
D. To describe what the test is supposed to do.

17 What does the 'DRY' principle in software development stand for?

Code quality and maintainability practices Easy
A. Document, Review, Yield
B. Data Rules You
C. Don't Repeat Yourself
D. Do Run Yourself

18 What is the process of 'refactoring' code?

Code quality and maintainability practices Easy
A. Adding a new feature from scratch.
B. Fixing a bug reported by a user.
C. Deleting old code that is no longer used.
D. Rewriting code to improve its internal structure without changing its external behavior.

19 Why is it important to write clear and meaningful variable names?

Code quality and maintainability practices Easy
A. It is a requirement for the code to compile.
B. It makes the code more readable and self-documenting.
C. It reduces the final bundle size of the application.
D. It makes the code run faster.

20 What is a primary benefit of creating types or interfaces for API responses in a frontend application?

Component and API typing strategies Easy
A. It forces the backend server to send data faster.
B. It is the only way to make an API call in TypeScript.
C. It provides editor autocompletion and type-checking for the response data.
D. It automatically handles all possible API errors.

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?

Type-safe data models Medium
A. An interface.
B. A type alias with a union.
C. A generic type alias.
D. A 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;
}

Type-safe data models Medium
A. Omit<User, 'email' | 'createdAt'>
B. Partial<User>
C. Pick<User, 'id' | 'name'>
D. Both 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-safe data models Medium
A. The use of the type keyword.
B. The presence of a data property in one state and an error property in another.
C. The union | operator combining different object shapes.
D. The 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?

Component and API typing strategies Medium
A. typescript
interface ButtonProps extends HTMLButtonElement {
variant: 'primary' | 'secondary';
}
B. typescript
type ButtonProps = {
variant: 'primary' | 'secondary';
onClick: () => void;
disabled?: boolean;
// ...manually add all other button props
};
C. typescript
type ButtonProps = {
variant: 'primary' | 'secondary';
} & React.ComponentProps<'button'>;
D. typescript
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?

Component and API typing strategies Medium
A. typescript
async function fetchData<T>(url: string): T { ... }
B. typescript
async function fetchData<T>(url: string): Promise<T> { ... }
C. typescript
async function fetchData<T>(url: string): Promise<any> { ... }
D. typescript
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?

Integration of TypeScript in frontend projects Medium
A. "compilerOptions": { "noImplicitAny": true }
B. "compilerOptions": { "alwaysStrict": true }
C. "compilerOptions": { "strict": true }
D. "compilerOptions": { "strictNullChecks": true }

27 What is the primary reason for using a linter like ESLint alongside the TypeScript compiler (tsc) in a project?

Static code analysis Medium
A. To check for type errors and ensure type safety.
B. To enforce code style, find programmatic errors, and identify code smells that don't violate type rules.
C. To manage project dependencies and install type declaration files.
D. To transpile TypeScript code into JavaScript for the browser.

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?

Debugging workflows Medium
A. They map the compiled JavaScript code back to the original TypeScript source code, allowing you to set breakpoints and inspect variables in your original .ts files.
B. They polyfill modern JavaScript features for older browsers.
C. They provide type information to the browser's debugger.
D. They bundle all JavaScript files into a single file for faster loading.

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?

Testing fundamentals Medium
A. To make the test run faster by using a local function.
B. To allow the component to be tested in a production environment.
C. To prevent the TypeScript compiler from throwing errors about the API's response type.
D. To isolate the component and test its rendering logic independently of external services, ensuring the test is deterministic and doesn't rely on a live network.

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

Code quality and maintainability practices Medium
A. It is a shorthand for casting, equivalent to myTheme as Theme.
B. It validates that myTheme's structure is assignable to Theme while preserving the inferred, more specific type of myTheme itself.
C. It forces myTheme to have only the properties defined in Theme, throwing an error on spacing.
D. It converts the 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?

Integration of TypeScript in frontend projects Medium
A. Search for and install a community-maintained types package, typically named @types/some-js-library.
B. Create a custom .d.ts file and declare the module with a basic type, like declare module 'some-js-library';
C. Rewrite the library in TypeScript yourself.
D. Set "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?

Static code analysis Medium
A. To automatically format the code according to Prettier rules.
B. To enable ESLint to run inside a web browser.
C. The default ESLint parser (Espree) only understands standard JavaScript syntax and cannot parse TypeScript-specific features like interfaces, enums, or type annotations.
D. To connect ESLint with the TypeScript compiler (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?
}

Component and API typing strategies Medium
A. discount: number | null;
B. discount: number?;
C. discount?: number;
D. discount?: number | null;

34 How does using TypeScript in your project enhance the quality and reliability of your tests, particularly when creating mock data?

Testing fundamentals Medium
A. It removes the need for mocking because all functions are type-safe.
B. It ensures that your test runner (like Jest) executes faster.
C. It allows you to use your defined interfaces and types (e.g., User, Product) to type your mock data, preventing tests from passing with invalid data shapes that would cause runtime errors.
D. It automatically generates unit tests for all your components.

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?

Debugging workflows Medium
A. It automatically adds try...catch blocks around your code to handle the error at runtime.
B. It forces every variable to be initialized with a non-null value, preventing undefined from ever occurring.
C. It forces you to explicitly handle cases where a value could be null or undefined before you can access its properties, flagging potential errors at compile time.
D. It converts all 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?

Code quality and maintainability practices Medium
A. Move all CSS styles into a separate .css file.
B. Combine the loading and error states into a single boolean isLoadingOrError.
C. Convert the component from a function component to a class component to better organize methods.
D. Extract the data-fetching and state-management logic into a custom hook (e.g., 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?

Testing fundamentals Medium
A. Unit Test
B. Static Type Test
C. Performance Test
D. Integration Test

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} />;

Component and API typing strategies Medium
A. React.ChangeEvent<HTMLInputElement>
B. any
C. Event
D. React.MouseEvent<HTMLInputElement>

39 When using a modern build tool like Vite, how is the TypeScript-to-JavaScript transformation process typically handled during development?

Integration of TypeScript in frontend projects Medium
A. Vite uses a faster transpiler like esbuild to strip TypeScript types and convert syntax to JavaScript on a per-file basis, but it does not perform type-checking.
B. Vite bundles all .ts files into one large .js file and then serves it to the browser.
C. Vite requires you to manually run tsc --watch in a separate terminal to handle all transformations.
D. Vite runs the full TypeScript compiler (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?

Type-safe data models Medium
A. An index signature, like Record<string, number>.
B. A class with a getter method.
C. An enum with numeric values.
D. A 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>>;

Type-safe data models Hard
A. Promise<{ user: string }>
B. any
C. unknown
D. { user: string }

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[]; }

Component and API typing strategies Hard
A. typescript
function withData<P extends object>(
WrappedComponent: React.ComponentType<P & InjectedProps>
): React.FC<P> {
// ... implementation
}
B. typescript
function withData<P>(
WrappedComponent: React.ComponentType<any>
): React.FC<P> {
// ... implementation
}
C. typescript
function withData<P extends InjectedProps>(
WrappedComponent: React.ComponentType<P>
): React.FC<Omit<P, keyof InjectedProps>> {
// ... implementation
}
D. typescript
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;
};

Type-safe data models Hard
A. typescript
{
onLogin: (payload: { userId: string }) => void;
onLogout: (payload: { reason:string }) => void;
}
B. typescript
{
login: (payload: { userId: string }) => void;
logout: (payload: { reason:string }) => void;
}
C. typescript
{
onLOGIN: (payload: { userId: string }) => void;
onLOGOUT: (payload: { reason:string }) => void;
}
D. The code will cause a syntax error because of the 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"
}
}

Integration of TypeScript in frontend projects Hard
A. The shared-logic tsconfig.json is missing the "composite": true compiler option.
B. The outDir in shared-logic should be ../webapp/node_modules/shared-logic.
C. The path in the webapp reference should be an absolute path.
D. The 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';
}

Testing fundamentals Hard
A. Write a test that checks isUser.prototype.constructor.name to be Function.
B. Write a test that passes a valid user object to isUser and asserts the result is true. Then, inside an if (isUser(obj)) block, access obj.name to ensure the test itself compiles.
C. Mock the User interface and use jest.isMockFunction to verify isUser was called.
D. Write two tests: one that asserts 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; }
}

Code quality and maintainability practices Hard
A. typescript
class Square extends Rectangle {
setWidth(value: number) {
this.width = value;
this.height = value;
}
setHeight(value: number) {
this.width = value;
this.height = value;
}
}
B. typescript
class Square extends Rectangle {
constructor(size: number) {
super();
this.width = size;
this.height = size;
}
}
C. typescript
class Square extends Rectangle {
setWidth(value: number | string) { // Widens input type
const numValue = Number(value);
this.width = numValue;
this.height = numValue;
}
// ... setHeight is similar
}
D. typescript
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.
});

Static code analysis Hard
A. Prefix the function call with the void operator: void doSomethingAsync();
B. Use a // eslint-disable-next-line @typescript-eslint/no-floating-promises comment.
C. Wrap the call in an IIFE: (async () => { await doSomethingAsync(); })();
D. Assign the promise to an unused variable: 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?

Debugging workflows Hard
A. The web server is not serving the .js.map files with the correct Content-Type header.
B. The browser's cache is serving an old version of the source map file but a new version of the JavaScript bundle.
C. The tsconfig.json has "sourceMap": false which overrides the bundler's configuration.
D. An optimization in the bundler (e.g., Webpack with Terser) has aggressively inlined functions or reordered code in a way that the source map generator could not accurately track.

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;
}

Component and API typing strategies Hard
A. The component should use a switch statement for the type guard to be effective.
B. You must use the in operator to check for the data property before accessing it.
C. The generic type T has not been constrained with extends object.
D. TypeScript's control flow analysis does not persist across separate, non-nested 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?

Integration of TypeScript in frontend projects Hard
A. typescript
import 'express';

interface Request {
currentUser?: MyUserType;
}
B. typescript
// This should be at the top level of a module
import { Request } from 'express';

Request.prototype.currentUser = undefined;
C. typescript
// In a regular .ts file, not a .d.ts file
import { Request } from 'express';

declare module 'express' {
interface Request {
currentUser?: MyUserType;
}
}
D. typescript
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;
}

Debugging workflows Hard
A. The generic constraint T must be T extends new (...args: any[]) => any for instanceof to work.
B. The check fails because 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.
C. The instanceof operator does not work with generic types. It should be replaced with typeof instance === 'T'.
D. The code is correct, but the 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;
}

Type-safe data models Hard
A. The code will produce a compiler error because recursive mapped types can lead to infinite loops.
B. A type where all properties, including function properties, are deeply readonly. The getData method will become readonly and cannot be reassigned.
C. typescript
{
readonly id: number;
readonly user: {
readonly name: string;
readonly address: {
readonly street: string;
};
};
readonly getData: () => string;
}
D. A type where only the top-level properties 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');

Testing fundamentals Hard
A. typescript
any
B. typescript
typeof ApiService
C. typescript
{ new(): { fetchData: jest.Mock } }
D. typescript
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);
}

Code quality and maintainability practices Hard
A. The compiler cannot guarantee that the key exists on all constituents of the union type Model. For example, price is not a key of User.
B. The type assertion key as keyof Model is incorrect; it should be key as 'name' | 'price'.
C. The generic function getProperty cannot handle union types for its first argument obj.
D. The 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?

Static code analysis Hard
A. The .eslintrc file is missing "parser": "@typescript-eslint/parser".
B. The eslint-plugin-typescript is deprecated and should be @typescript-eslint/eslint-plugin.
C. Node.js version mismatch between the environment running tsc and the one running eslint.
D. ESLint's parser is configured to use a different 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-safe data models Hard
A. typescript
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;
B. typescript
type Curry<F extends (...args: any) => any> = (arg: Parameters<F>[0]) => ReturnType<F>;
C. typescript
type Curry<A extends any[], R> = (head: A[0], ...tail: A) => Curry<typeof tail, R>;
D. typescript
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?

Component and API typing strategies Hard
A. It is a generic utility that extracts all valid props (attributes) from a given component or tag name C, excluding ref, allowing attributes like href for <a> or onClick for <button> to be type-checked.
B. It merges the props of C with the props of a base <div> element for default attributes.
C. It ensures that the as prop itself is one of the valid HTML tags like 'div', 'a', or 'span'.
D. It is a utility that only extracts 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];

Code quality and maintainability practices Hard
A. enum members are transpiled into more performant JavaScript code than object lookups.
B. An 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.
C. as const objects cannot be iterated over at runtime, whereas enums can.
D. An 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; }

Integration of TypeScript in frontend projects Hard
A. The JSDoc comment is malformed; it should use @type instead of @param for imports.
B. The User type is an interface, which cannot be referenced from JSDoc in .js files; it must be a type alias or a class.
C. The import('./types').User syntax requires moduleResolution to be set to nodenext or node16 in tsconfig.json for JSDoc.
D. The @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]);
}

Testing fundamentals Hard
A. Write multiple it blocks, each with a different concrete type (e.g., pluck(users, 'name'), pluck(products, 'price')) and assert the runtime values.
B. Use jest.fn() to mock the pluck function and test its call signatures.
C. Cast the function's return value with as any to avoid type errors in tests and only focus on the runtime logic.
D. Use a tool like tsd or expect-type to write compile-time assertions that check the inferred return type of the function, in addition to runtime expect calls.