All quizzesMedium
Utility Types
Preview — 3 of 10 questions
What does keyof T produce and how is it used here?
javascript
function getProperty<T, K extends keyof T>(obj: T, key: K): T[K] {
return obj[key];
}
const user = { id: "1", name: "Alice", age: 30 };
const name = getProperty(user, "name");
const id = getProperty(user, "id");
const x = getProperty(user, "missing"); // ?Aname is string, id is string, "missing" causes a compile error
BAll three work — any string key is accepted
CAll return unknown
DgetProperty only works on objects with exactly 3 properties
What does this mapped type produce?
javascript
type Stringify<T> = {
[K in keyof T]: string;
};
interface User {
id: number;
name: string;
active: boolean;
}
type StringUser = Stringify<User>;A{ id: number; name: string; active: boolean } — unchanged
B{ id: string; name: string; active: string } — all values become string
C{ [key: string]: string } — loses property names
Dstring[] — an array of strings
What is the effect of Readonly<T>?
javascript
interface Config {
host: string;
port: number;
}
const config: Readonly<Config> = {
host: "localhost",
port: 3000,
};
config.host = "production.server.com"; // ?
config.port = 8080; // ?ABoth assignments work — Readonly has no runtime effect
BBoth assignments cause compile errors — Readonly<T> makes all properties readonly
Cconfig.host allows mutation; config.port does not
DReadonly only affects nested objects, not primitives
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.