All quizzesMedium
Template Literals & Inference — Series 2
Preview — 3 of 10 questions
javascript
type Join<T extends string[]> = T extends [infer First extends string, ...infer Rest extends string[]]
? Rest extends []
? First
: `${First}.${Join<Rest>}`
: "";
type Path = Join<["user", "profile", "email"]>;APath is "user" — only the first element of the tuple is ever used
BPath is "user.profile.email" — the recursive conditional type walks through the tuple element by element, joining each with a . until it reaches (and returns) the last one
CCompile-time error — recursive template literal types aren't supported by TypeScript
DPath is string, since template literal types can't preserve an exact literal result through recursion
javascript
interface Config {
readonly host: string;
readonly port?: number;
}
type MutableRequired<T> = { -readonly [K in keyof T]-?: T[K] };
type EditableConfig = MutableRequired<Config>;
const c: EditableConfig = { host: "localhost", port: 8080 };
c.host = "example.com";
const bad: EditableConfig = { host: "localhost" };AEditableConfig is identical to Config — the - prefixes have no actual effect on the resulting type
Bc.host = "example.com" is a compile-time error, since MutableRequired doesn't actually remove readonly from the properties
Cbad compiles fine, since -? only strips readonly, not optionality
Dc.host = "example.com" compiles fine, because -readonly removes the read-only modifier from every property; and bad is a compile-time error, because -? removes the optional modifier from every property, making port a required field that bad fails to provide
javascript
interface Events {
click: MouseEvent;
keydown: KeyboardEvent;
}
type Handlers = { [K in keyof Events as `on${Capitalize<K & string>}`]: (e: Events[K]) => void };
declare const handlers: Handlers;
handlers.onClick(new MouseEvent("click"));
handlers.click;AHandlers has properties onClick and onKeydown (each a handler function); handlers.onClick(...) compiles fine, but handlers.click is a compile-time error, since the original key click was renamed via as and no longer exists on Handlers
BHandlers ends up with both the original keys (click, keydown) and the renamed ones (onClick, onKeydown)
CCompile-time error — mapped types are only allowed to change a property's value type, never its key name
DHandlers has properties onClick and onKeydown, but both calls in the example are compile-time errors
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.