Advanced Generics — Series 2

Preview — 3 of 10 questions

javascript
type MyReturnType<T> = T extends (...args: any[]) => infer R ? R : never;
type Fn = (a: number, b: string) => boolean;
type Result = MyReturnType<Fn>;
Anever
Bany
C(a: number, b: string) => boolean
Dboolean

javascript
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] {
  return obj[key];
}
const user = { name: 'Alice', age: 30 };
const name = getProp(user, 'name');
const invalid = getProp(user, 'email');
AgetProp(user, 'name') compiles fine (name: string); getProp(user, 'email') is a compile-time error, because 'email' isn't assignable to K extends keyof T, which resolves to 'name' | 'age'
BBoth lines compile fine; TypeScript infers K as string automatically for any key
CBoth lines throw a runtime TypeError
DOnly the 'email' call compiles; the 'name' call errors because T[K] can't be inferred

javascript
type Tuple = [string, number, boolean];
type Union = Tuple[number];
A[string, number, boolean] (unchanged)
Bstring | number | boolean
Cstring (only the first element's type)
Dnever

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.