Type a destructured options parameter and return a typed tuple
connect takes a single options object, destructured in the parameter list, and returns the host it connected to together with the number of attempts it is allowed to make.
Requirements:
- the destructured parameter must be typed (
hostrequired,retriesoptional); retriesdefaults to3and must be a plainnumberinside the body;- the returned pair must be typed
[string, number], not(string | number)[].
export function connect({ host, retries }) {
// your code here
}
Write the implementation.
The annotation goes on the whole pattern, not the names inside: ({ host, retries = 3 }: { host: string; retries?: number }). The default narrows retries to plain number in the body. The return needs : [string, number] — inference widens the literal to (string | number)[].
- ✗Writing
{ host: string }in the pattern, which renameshosttostringinstead of typing it - ✗Expecting the returned array literal to be inferred as a tuple
- ✗Thinking a default inside the pattern still leaves the name typed
T | undefined
- →What does
as conston the returned array literal give you instead? - →Why does a destructured array element lose its position without a tuple annotation?
The annotation on a destructured parameter belongs to the whole pattern and is written after the closing brace. Writing { host: string } inside the pattern is not a type — it renames host to a variable called string.
export function connect(
{ host, retries = 3 }: { host: string; retries?: number },
): [string, number] {
// `retries` is a plain number here: the default is applied, undefined is gone
return [host, retries];
}
const [h, n] = connect({ host: 'db.local' }); // h: string, n: number
Two places where inference will not give you what you want:
(string | number)[] — an array, not a tuple: the positions are lost and n would need narrowing. Annotating : [string, number] (or as const on the literal, which yields readonly [string, number]) keeps them.
pattern removes the undefined, so no check is needed inside.
- The return type. Without an annotation,
[host, retries]is inferred as - The default.
retries?: numberisnumber | undefinedin the body, but= 3in the