All quizzesMedium
Utility Types — Series 3
Preview — 3 of 10 questions
javascript
declare function setProp<T, K extends keyof T>(obj: T, key: K, value: T[K]): void;
const user = { id: 1, name: "Ada" };
setProp(user, "name", "Grace");
setProp(user, "name", 42);ABoth compile — T[K] widens to the union of all the object's value types
BBoth fail — T and K cannot both be inferred from the same call
CThe first compiles; the second is a compile-time error — T["name"] is string, so 42 isn't assignable
DThe first fails — "Grace" isn't the literal type "Ada" that was inferred for the property
javascript
type Stringify<T> = { [K in keyof T]: string };
type R = Stringify<{ a: number; b: boolean }>;A{ a: string; b: string }
B{ a: number; b: boolean } — the value type in a mapped type is ignored
C{ [x: string]: string } — mapping erases the specific keys
DCompile-time error — a mapped type's value must reference T[K]
javascript
type Config = Readonly<{ db: { host: string } }>;
declare const cfg: Config;
cfg.db = { host: "a" };
cfg.db.host = "b";ABoth assignments fail — Readonly applies recursively
BBoth compile — Readonly is erased at compile time and enforces nothing
CThe first compiles, the second fails
DThe first fails, the second compiles — Readonly<T> marks only the top-level properties
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.