Unit 5 - Practice Quiz

INT219 61 Questions
0 Correct 0 Wrong 61 Left
0/61

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

Introduction to TypeScript Easy
A. It does not require a compilation step.
B. It automatically optimizes images.
C. It adds static type-checking to JavaScript.
D. It runs faster in the browser.

2 Which company developed and maintains TypeScript?

Introduction to TypeScript Easy
A. Oracle
B. Google
C. Facebook
D. Microsoft

3 What does the TypeScript compiler (tsc) convert TypeScript code into?

TypeScript compilation workflow Easy
A. JavaScript Code
B. Java Code
C. Machine Code
D. Python Code

4 How do you explicitly assign a string type to a variable named username in TypeScript?

Type system and annotations Easy
A. let username is string;
B. let username: string;
C. string username;
D. let username = string;

5 Which built-in type in TypeScript can hold true or false values?

Type system and annotations Easy
A. number
B. boolean
C. string
D. any

6 Which keyword is used to create a new name for a type, such as a union of other types?

Interfaces and type aliases Easy
A. alias
B. type
C. interface
D. typedef

7 What is the primary purpose of an interface in TypeScript?

Interfaces and type aliases Easy
A. To perform mathematical calculations.
B. To define a new logical operator.
C. To create a new variable.
D. To define the shape or structure of an object.

8 Which character is used to create a union type, allowing a variable to be one of several types?

Union and intersection types Easy
A. ? (question mark)
B. & (ampersand)
C. % (percent)
D. | (pipe)

9 What is type inference in TypeScript?

Type inference and narrowing Easy
A. A type of runtime error.
B. When the compiler automatically determines a variable's type based on its initial value.
C. Manually converting a variable from one type to another.
D. A feature for creating generic functions.

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

TypeScript compilation workflow Easy
A. .tsc
B. .ts
C. .tsx
D. .js

11 What does the any type represent in TypeScript?

Type system and annotations Easy
A. A type for functions only.
B. A value that can be of any type, effectively disabling type-checking.
C. A value that must be a number.
D. A value that is guaranteed to be null or undefined.

12 What is the main advantage of using generics in TypeScript?

Generics Easy
A. To reduce the final JavaScript bundle size.
B. To make code run faster.
C. To automatically generate documentation.
D. To create components that can work with a variety of types rather than a single one.

13 Given let score = 100;, what type does TypeScript infer for the score variable?

Type inference and narrowing Easy
A. boolean
B. number
C. string
D. any

14 What does the type string & number resolve to?

Union and intersection types Easy
A. string | number
B. never
C. number
D. string

15 In the context of generics, what does T in <T> typically stand for?

Generics Easy
A. True
B. Type
C. Timestamp
D. Table

16 Is TypeScript a statically typed or a dynamically typed language?

Introduction to TypeScript Easy
A. Dynamically typed
B. Both
C. Statically typed
D. Neither

17 What is the most common name for the TypeScript configuration file?

TypeScript compilation workflow Easy
A. typescript.json
B. tsconfig.json
C. config.ts
D. package.json

18 What is the purpose of using a typeof check inside an if statement in TypeScript?

Type inference and narrowing Easy
A. To change the type of a variable.
B. To check if a file exists.
C. To help TypeScript narrow down a broad type to a more specific one within that block.
D. To measure the performance of a function.

19 Can a class implement an interface in TypeScript?

Interfaces and type aliases Easy
A. No, interfaces are only for objects.
B. Only if the interface has no properties.
C. Yes, using the implements keyword.
D. Yes, using the extends keyword.

20 How would you define an array of numbers in TypeScript?

Type system and annotations Easy
A. Array<number> or number[]
B. [number]
C. numbers()
D. array: number

21 What is the primary reason for using TypeScript in a large, team-based JavaScript project?

Introduction to TypeScript Medium
A. It offers a richer standard library than JavaScript.
B. It transpiles modern JavaScript features for older browsers.
C. It automatically optimizes the runtime performance of the code.
D. It provides static type-checking to catch errors during development, improving code quality and maintainability.

22 Consider the following code. What will be the output of the TypeScript compiler?

typescript
let data: unknown;
data = "Hello, world!";

// What happens at this line?
console.log(data.toUpperCase());

Type system and annotations Medium
A. The code fails to compile with an error: 'Object is of type 'unknown'.'
B. The code compiles successfully and prints "HELLO, WORLD!".
C. The code compiles, but throws a runtime error because data is unknown.
D. The code compiles successfully but prints undefined.

23 Which of the following statements accurately describes a key difference between interface and type aliases in TypeScript?

Interfaces and type aliases Medium
A. Only interface can be implemented by a class.
B. interface declarations can be merged (declaration merging), while type aliases cannot.
C. Only type aliases can be used to define union types.
D. type aliases are hoisted, but interface declarations are not.

24 Given the following types, which object is a valid instance of AdminUser?

typescript
type User = {
id: number;
name: string;
};

type Admin = {
id: number;
permissions: string[];
};

type AdminUser = User & Admin;

Union and intersection types Medium
A. { id: 1, name: 'Alice', permissions: ['read'] }
B. { name: 'Bob', permissions: ['delete'] }
C. { id: 1, name: 'Alice' }
D. { id: 1, permissions: ['write'] }

25 What is the purpose of the extends keyword in the following generic function signature?

typescript
function getProperty<T, K extends keyof T>(obj: T, key: K) {
return obj[key];
}

Generics Medium
A. It specifies that K must be a type that is assignable to one of the keys of T.
B. It ensures that T is a subclass of K.
C. It allows the function to extend the properties of the object T.
D. It is used for inheritance between generic types T and K.

26 Analyze the code below. What is the inferred type of the statusMessage variable?

typescript
function getStatus(code: number) {
if (code < 400) {
return { success: true, code };
} else {
return { success: false, error: Error code: ${code} };
}
}

const statusMessage = getStatus(200);

Type inference and narrowing Medium
A. any
B. { success: boolean; code: number; error: string; }
C. { success: true; code: number; } | { success: false; error: string; }
D. { success: boolean; code?: number; error?: string; }

27 What is the primary effect of setting "noImplicitAny": true in the tsconfig.json file?

TypeScript compilation workflow Medium
A. It automatically converts all any types to unknown during compilation.
B. It forces the developer to explicitly use unknown instead of any.
C. It disables the use of the any type completely throughout the project.
D. It raises a compiler error on variables and parameters that have an implicit any type.

28 Which type annotation should be used for the employee parameter in the following function to ensure it receives an array where the first element is a string (name) and the second is a number (id)?

typescript
function processEmployee(/ employee: ??? /) {
const name = employee[0]; // should be string
const id = employee[1]; // should be number
}

Type system and annotations Medium
A. {string, number}
B. Array<string | number>
C. (string | number)[]
D. [string, number]

29 Given the following Logger interface and FileLogger class, why does the TypeScript compiler show an error?

typescript
interface Logger {
log(message: string): void;
}

class FileLogger implements Logger {
log(message: string, level: string): void {
console.log([{message});
}
}

Interfaces and type aliases Medium
A. Interfaces cannot be implemented by classes in TypeScript.
B. The log method in FileLogger has a different method signature than the one defined in the Logger interface.
C. The class is missing the implements Logger clause.
D. The log method in the interface must be marked as public.

30 Why does the following function produce a TypeScript error?

typescript
function formatInput(input: string | number) {
// Error on the next line
return input.trim();
}

Union and intersection types Medium
A. The function must have an explicit return type annotation.
B. The trim method does not exist on the number type, and TypeScript cannot guarantee input is a string.
C. Union types are not allowed as function parameters.
D. The input parameter must be an intersection type (string & number) to have methods from both types.

31 Consider this generic interface. Which of the following variable declarations is valid?

typescript
interface ApiResponse<T> {
data: T;
status: number;
}

interface User {
id: number;
username: string;
}

Generics Medium
A. const response: ApiResponse<User> = { data: { id: 1, username: 'test' }, status: 200 };
B. const response: ApiResponse<User> = { data: { id: 1 }, status: 200 };
C. const response: ApiResponse = { data: { id: 1, username: 'test' }, status: 200 };
D. const response: ApiResponse<User> = { data: 'some user', status: 404 };

32 In the code below, what is the type of pet inside the if block?

typescript
interface Cat {
meow(): void;
}

interface Dog {
bark(): void;
}

function makeSound(pet: Cat | Dog) {
if ('bark' in pet) {
// What is the type of pet here?
pet.bark();
}
}

Type inference and narrowing Medium
A. any
B. Cat | Dog
C. Dog
D. Cat

33 What is the primary use case for creating a type alias for a union of string literals, as shown below?

typescript
type OrderStatus = 'pending' | 'shipped' | 'delivered' | 'cancelled';

let currentStatus: OrderStatus = 'pending';

Interfaces and type aliases Medium
A. To allow currentStatus to be any string at runtime.
B. To combine the properties of multiple string objects.
C. To create a new class named OrderStatus.
D. To restrict the possible string values that can be assigned to currentStatus, providing type safety and autocompletion.

34 Which of the following function calls would cause a TypeScript compilation error?

typescript
function merge<T extends object, U extends object>(objA: T, objB: U) {
return { ...objA, ...objB };
}

Generics Medium
A. merge({ id: 1 }, { data: ['a', 'b'] })
B. merge({ value: null }, { enabled: true })
C. merge({ name: 'Max' }, { age: 30 })
D. merge({ name: 'Max' }, 30)

35 Consider the following discriminated union. Why is the access to c inside the 'circle' case valid?

typescript
interface Square { kind: 'square'; size: number; }
interface Circle { kind: 'circle'; radius: number; }
type Shape = Square | Circle;

function getArea(s: Shape) {
switch (s.kind) {
case 'square': return s.size s.size;
case 'circle': return Math.PI
s.radius ** 2;
}
}

Type inference and narrowing Medium
A. The compiler implicitly casts s to type any inside the switch statement.
B. This code will actually produce a compiler error.
C. The switch statement on the kind property narrows the type of s to Circle within that case block.
D. Because radius is an optional property on the Shape type.

36 What is the resulting type of Combined?

typescript
interface A { a: number; b: string; }
interface B { b: number; c: boolean; }

type Combined = A & B;

Union and intersection types Medium
A. { a: number; b: never; c: boolean; }
B. { a: number; b: string | number; c: boolean; }
C. { a: number; b: any; c: boolean; }
D. { a: number; b: number; c: boolean; }

37 How does TypeScript relate to the ECMAScript (ES) standard?

Introduction to TypeScript Medium
A. TypeScript is a completely separate language that does not follow ECMAScript standards.
B. TypeScript only supports syntax from the ES5 version of ECMAScript.
C. TypeScript is a strict syntactical superset of JavaScript and aims to align with future ECMAScript proposals.
D. TypeScript is a competing standard to ECMAScript, proposed by Microsoft.

38 A function is intended to accept a callback that takes no arguments and doesn't return a value. What is the correct type annotation for the callback parameter?

typescript
function executeCallback(callback: / ??? /) {
callback();
}

Type system and annotations Medium
A. Function
B. () => void
C. (any) => any
D. void

39 You want to create a function that takes an array of any type and returns a new array with duplicate values removed. Which function signature is the most appropriate and type-safe?

typescript
// function unique(arr: ???): ??? { ... }

Generics Medium
A. unique(arr: unknown[]): unknown[]
B. unique<T>(arr: Array<T>): Array<any>
C. unique<T>(arr: T[]): T[]
D. unique(arr: any[]): any[]

40 What happens if a class implements an interface with an optional property, but the class does not declare that property?

typescript
interface Options {
timeout?: number;
retries: number;
}

class Config implements Options {
retries: number = 3;
}

Interfaces and type aliases Medium
A. TypeScript will automatically add a timeout property of type any to the Config class.
B. TypeScript will throw a compilation error because timeout is missing.
C. The code will compile without errors.
D. A runtime error will occur when an instance of Config is created.

41 Consider the following TypeScript code. What is the inferred type of result?

typescript
function keyRemover<T, K extends keyof T>(obj: T, key: K): Omit<T, K> {
const { [key]: _, ...rest } = obj;
return rest;
}

const user = {
id: 1,
name: 'Alice',
email: 'alice@example.com'
};

const keyToOmit = 'id' as const;
const result = keyRemover(user, keyToOmit);

Generics Hard
A. The type of result is inferred as Omit<{ id: number; name: string; email: string; }, "id">.
B. The type of result is inferred as Partial<{ name: string; email: string; }>.
C. The type of result is { name: string; email: string; }.
D. The code fails to compile because destructuring with a dynamic key [key] is not type-safe for creating an Omit type.

42 Analyze the following TypeScript function. Which statement accurately describes the type of data at the marked point?

typescript
type Success = { status: 'success'; data: string };
type Loading = { status: 'loading' };
type Error = { status: 'error'; error: Error };
type State = Success | Loading | Error;

function processState(state: State) {
if (state.status === 'success' || state.status === 'loading') {
return;
}
// What is the type of state here?
const { error } = state;
console.log(error.message);
}

Type inference and narrowing Hard
A. The type of state is State, and the code compiles without error.
B. The type of state is narrowed to Error.
C. The code throws a compile-time error because state is of type Error, but Error is also the name of a built-in JavaScript class, causing a conflict.
D. The type of state is never, because all possible cases are handled in the if block.

43 What is the resulting type of Combined and why?

typescript
type FuncA = (a: string, b: number) => void;
type FuncB = (a: string) => void;

type Combined = FuncA & FuncB;

const fn: Combined = (a: string, b?: number) => {};

Union and intersection types Hard
A. An intersection of two functions is not possible and results in a compile-time error.
B. Combined is an overloaded function type that can be called with either (a: string, b: number) or (a: string). The implementation must be compatible with the most specific signature, (a: string, b: number) => void.
C. Combined is a single function signature (a: string, b: number) => void, because it's the more specific of the two, and fn is a valid implementation.
D. Combined is a single function signature (a: string) => void, because it's the more lenient of the two.

44 Given the following interface with an index signature, why does the TypeScript compiler raise an error?

typescript
interface StringMap {
[key: string]: string;
length: number;
}

Interfaces and type aliases Hard
A. The length property is missing an explicit public accessor.
B. The property length is a reserved keyword and cannot be used in interfaces.
C. Index signatures cannot be mixed with explicitly named properties.
D. The type of the length property, number, is not assignable to the value type of the string index signature, string.

45 What is the behavior of the following conditional type IsString<T> when applied to a union type?

typescript
type IsString<T> = T extends string ? true : false;

type Result = IsString<string | number>;

Generics Hard
A. Result is false, because the entire union string | number does not extend string.
B. Result is boolean, because the condition is checked for each member of the union, resulting in true | false.
C. Result is true, because at least one member of the union extends string.
D. This code results in a compile-time error because conditional types cannot be applied to union types directly.

46 In the context of function types, what do covariance and contravariance refer to, and which example correctly demonstrates one of them?

typescript
class Animal {}
class Dog extends Animal {}

// Which assignment is valid and why?
let processAnimal: (a: Animal) => void;
let processDog: (d: Dog) => void;

Type system and annotations Hard
A. processDog = processAnimal; is valid. This is covariance, where a function can accept a more general type in place of a specific one.
B. processAnimal = processDog; is valid. This is covariance, as the parameter type is more specific.
C. Neither assignment is valid due to a strict type mismatch in function parameters.
D. processDog = processAnimal; is valid. This is contravariance, where a function expecting a more specific type can be assigned a function that handles a more general type.

47 You have a project with "noEmitOnError": true in your tsconfig.json. You run tsc and it reports a single type error in file.ts. What is the state of your output directory (e.g., dist) after the compilation attempt?

TypeScript compilation workflow Hard
A. dist/file.js is generated, but it contains comments indicating where the type error occurred.
B. No files will be written to the output directory at all.
C. The entire output directory is created, but dist/file.js will be missing.
D. All files, including dist/file.js, are generated, but the compiler exits with a non-zero status code.

48 What is the evaluated type of Result? Analyze the interaction between the mapped type and the intersection.

typescript
type Properties = 'name' | 'age';
type Mapped = { [K in Properties]: { [P in K]: P extends 'name' ? string : number } };

type Result = Mapped['name'] & Mapped['age'];

Union and intersection types Hard
A. A compile-time error occurs.
B. { name: string; } | { age: number; }
C. { name: string; age: number; }
D. never

49 Examine this custom type guard. Why is it considered an anti-pattern or potentially unsafe, despite compiling successfully?

typescript
interface Car { drive: () => void; }
interface Bike { ride: () => void; }

function isCar(vehicle: Car | Bike): vehicle is Car {
return (vehicle as Car).drive !== undefined;
}

const myBike: Bike = { ride: () => {} };

if (isCar(myBike)) {
// What is problematic here?
myBike.drive(); // Compiles, but will crash at runtime
}

Type inference and narrowing Hard
A. The property check 'drive' in vehicle is a more robust way to check for the property's existence and should be used instead.
B. The type guard is unsafe because an object could have a drive property with a value of null or undefined, which would satisfy the check but not be a function.
C. The type guard should use instanceof Car instead of property checking.
D. The type guard's return type vehicle is Car is incorrect; it should be boolean.

50 What is the inferred return type of the getDeepValue function in the following example?

typescript
function getDeepValue<T, K1 extends keyof T, K2 extends keyof T[K1]>(obj: T, key1: K1, key2: K2): T[K1][K2] {
return obj[key1][key2];
}

const data = {
user: {
id: 1,
name: 'John Doe',
address: {
street: '123 Main St',
city: 'Anytown'
}
},
posts: []
};

const cityName = getDeepValue(data, 'user', 'address');

Generics Hard
A. The code fails to compile because the call is missing the third argument corresponding to K2.
B. The inferred type of cityName is { street: string; city: string; }.
C. The code fails to compile because K2 cannot be constrained by keyof T[K1].
D. The inferred type of cityName is unknown because the depth is too complex for TypeScript.

51 Given the following function that uses variadic tuple types and a const assertion, what is the inferred type of tupleTail?

typescript
function tail<T extends any[]>(arr: readonly [any, ...T]) : T {
const [_head, ...rest] = arr;
return rest;
}

const myTuple = [10, 'hello', true] as const;
const tupleTail = tail(myTuple);

Generics Hard
A. readonly ['hello', true]
B. (string | boolean)[]
C. [string, boolean]
D. ['hello', true]

52 What will be the type of config.apiKey and why does the following code behave as it does?

typescript
interface BaseConfig {
readonly apiKey: string;
}

interface Config extends BaseConfig {
apiKey: string; // Attempt to override readonly
}

function setKey(config: Config) {
config.apiKey = 'new-key'; // Is this allowed?
}

const myConfig: Config = { apiKey: 'old-key' };
setKey(myConfig);

Interfaces and type aliases Hard
A. The code compiles. config.apiKey is mutable (string) because the extending interface Config overrides the readonly modifier.
B. The code fails to compile at the setKey function call because myConfig's apiKey is implicitly readonly.
C. The code compiles, but a runtime error is thrown when trying to modify config.apiKey.
D. The code fails to compile because Config cannot override readonly apiKey with a mutable one.

53 Consider the assert function below. After the assertion, person.name can be used as a string. What TypeScript concept makes this possible?

typescript
interface Person {
name?: string;
age: number;
}

function assert(condition: unknown, msg?: string): asserts condition {
if (!condition) {
throw new Error(msg);
}
}

function processPerson(person?: Person) {
assert(person, 'Person must be defined');
// person is now of type Person

assert(typeof person.name === 'string', 'Person must have a name');
// person.name is now of type string
console.log(person.name.toUpperCase());
}

Type inference and narrowing Hard
A. This works because assert returns the never type, which signals to the compiler that code execution halts on a false condition.
B. The compiler automatically narrows types inside any function named assert.
C. This is a feature of the unknown type, which allows the compiler to infer types after a check.
D. This is possible due to the special asserts condition return type, which acts as an assertion function for control flow analysis.

54 What is the type of Keys in the snippet below?

typescript
type A = { a: string; common: number };
type B = { b: string; common: string };

type Keys = keyof (A | B);

Union and intersection types Hard
A. 'a' | 'b' | 'common'
B. 'common'
C. 'a' | 'b'
D. never

55 What is the primary reason the following code produces a compile-time error?

typescript
function createInstance<T>(constructor: { new(): T }): T {
return new constructor();
}

class MyClass {
private name: string;
constructor() { this.name = 'instance'; }
}

// Error occurs on the line below
const instance = createInstance(MyClass);

Generics Hard
A. The generic function cannot instantiate a class with private members.
B. The constraint { new(): T } does not match MyClass because it refers to the public-facing constructor, and MyClass has private instance members, which affects its structural compatibility.
C. The createInstance function should be called with new createInstance(MyClass).
D. MyClass is a type, not a value, and cannot be passed as an argument.

56 You have two files, math.ts and app.ts. You want to create a single JavaScript output file bundle.js and a corresponding declaration file bundle.d.ts. Which combination of tsconfig.json settings and compiler command is most appropriate?


// tsconfig.json
{
"compilerOptions": {
"target": "es2020",
"module": "amd",
/ Add settings here /
}
}

TypeScript compilation workflow Hard
A. "outFile": "./dist/bundle.js", "declaration": true and run tsc --project .. This will fail because outFile is only supported for amd and system modules.
B. "outFile": "./dist/bundle.js", "declaration": true and run tsc.
C. "outDir": "./dist", "declaration": true and run tsc app.ts math.ts --out dist/bundle.js.
D. "outDir": "./dist", "declaration": true and use a bundler like Webpack or Rollup, as tsc cannot bundle multiple files into one with declaration files unless using amd or system modules.

57 You want to compile your TypeScript project into a single JavaScript file named bundle.js and a corresponding bundle.d.ts. Given the tsconfig.json below, what is the outcome when running tsc?


{
"compilerOptions": {
"target": "es2020",
"module": "es2020",
"declaration": true,
"outFile": "./dist/bundle.js"
},
"include": ["src/*/.ts"]
}

TypeScript compilation workflow Hard
A. The command succeeds, but only dist/bundle.js is created because declaration files cannot be bundled.
B. The compiler issues a warning but proceeds to create the bundled files.
C. The command succeeds, creating dist/bundle.js and dist/bundle.d.ts.
D. The compiler issues an error because the outFile option cannot be used when the module is not None, System, or AMD.

58 What is the key difference in behavior between any and unknown in the following code, and why does one line fail to compile?

typescript
function processData(data: any, data2: unknown) {
console.log(data.property.name); // Line 1
console.log(data2.property.name); // Line 2: Compile Error
}

Type system and annotations Hard
A. any effectively disables all type checking for the variable, allowing any operation. unknown is a type-safe top type that requires type assertion or narrowing before operations are permitted.
B. any is a top type, while unknown is a bottom type. Accessing properties on a bottom type is forbidden.
C. Using unknown causes the compiler to automatically attempt to infer a more specific type, which fails here. any does not trigger this inference.
D. Both are top types, but any is inferred by the compiler when no type is provided, whereas unknown must be explicitly annotated.

59 TypeScript's type system is primarily described as "structural". What does this mean in practice, and how does it differ from a "nominal" type system?

typescript
class User {
id: number;
name: string;
}

class Product {
id: number;
name: string;
}

function printName(obj: User) {
console.log(obj.name);
}

const p = new Product();
p.id = 1;
p.name = 'Laptop';

printName(p); // Why does this work?

Introduction to TypeScript Hard
A. It is a nominal system; the code works because Product implicitly extends User.
B. It is a nominal system, but TypeScript has a special exception for classes with identical property names.
C. It is a structural system; the code works because the Product instance has the same shape (or structure) of properties and types required by the User type.
D. It is a structural system, but this only applies to type aliases, not class instances. The code has a hidden type error.

60 In the following code, what is the type of x after the switch statement, and why?

typescript
function check(value: string | number | boolean) {
let x: string | number;
switch (typeof value) {
case 'string':
x = value;
break;
case 'number':
x = value;
break;
default:
// The 'boolean' case is not handled
// What is the type of x here?
// A value must be assigned to x before it is used.
// To make this compile, let's assume it's used after the switch.
}
// return x; // This would cause an error: 'x' is possibly 'undefined'.
}

Let's refine the question. What happens if we try to use x immediately after the switch?
typescript
function check(value: string | number | boolean) {
let x: string | number;
switch (typeof value) {
case 'string': x = value; break;
case 'number': x = value; break;
}
return x; // What is the error here?
}

Type inference and narrowing Hard
A. The function returns string | number. There is no error.
B. The function fails to compile with the error "Type 'undefined' is not assignable to type 'string | number'." because control flow analysis determines x could be unassigned.
C. The type of x is never because the default case in the switch is unhandled.
D. The function fails to compile with the error "Variable 'x' is used before being assigned." because the boolean case doesn't assign to x.

61 Analyze the following mapped type. What is the resulting structure of EventMap?

typescript

type Route = '/users' | '/posts';

type Methods<R extends Route> = R extends '/users'
? 'GET' | 'POST'
: 'GET';

type EventMap = {
[R in Route]: {
method: Methods<R>;
handler: (req: { route: R }) => void;
}
};

Generics Hard
A. typescript
{
'/users': { method: 'GET' | 'POST'; handler: (req: { route: '/users' }) => void; };
'/posts': { method: 'GET'; handler: (req: { route: '/posts' }) => void; };
}
B. A compile-time error occurs because Methods<R> cannot be resolved within the mapped type.
C. typescript
{
[R in Route]: { method: 'GET' | 'POST'; handler: (req: { route: R }) => void; }
}
D. typescript
{
'/users': { method: 'GET' | 'POST'; handler: (req: { route: '/users' | '/posts' }) => void; };
'/posts': { method: 'GET'; handler: (req: { route: '/users' | '/posts' }) => void; };
}