Errata

TypeScript Cookbook

Errata for TypeScript Cookbook

Submit your own errata for this product.

The errata list is a list of errors and their corrections that were found after the product was released.

The following errata were submitted by our customers and have not yet been approved or disproved by the author or editor. They solely represent the opinion of the customer.

Color Key: Serious technical mistake Minor technical mistake Language or formatting error Typo Question Note Update

Version Location Description Submitted by Date submitted
Other Digital Version 2.4. Working with Tuple Types
Last example code

The argument of the function hello is "msg: string", it should be "age: number".
The return type should be "void".

i.e.
When you need to collect arguments in your code, you can use a tuple before you apply them to your function:

const person: [string, number] = ["Stefan", 40];

function hello(...args: [name: string, msg: string]):
{
//...
}

should be:

When you need to collect arguments in your code, you can use a tuple before you apply them to your function:

const person: [string, number] = ["Stefan", 40];

function hello(...args: [name: string, age: number]): void
{
//...
}

Ting-Chong Ma  Feb 04, 2024 
ePub Page 7.6 Creating an Enum from a Tuple
Page 341 of 651 (Kindle eBook)

Dear Stefan,

I tried the final example code in TS Playground and VS Code and get the following errors:
Type 'K["key"]' does not satisfy the constraint 'string'.
Type 'TupleToUnion<T>["key"]' is not assignable to type 'string'.
Type '"key"' cannot be used to index type 'K'.
Type '"val"' cannot be used to index type 'K'.
Type '"key"' cannot be used to index type 'K'.

I already corrected the code as listed below (const instead of let and 'single quotes' instead of "double quotes"):
type TupleToUnion<T extends readonly string[]> =
T extends readonly [...infer Rest extends string[], infer Key extends string] ? Key
| TupleToUnion<Rest> : never;

type Enum<T extends readonly string[], N extends boolean = false> = Readonly<{
[K in TupleToUnion<T> as Capitalize<K['key']>]: N extends true ? K['val'] : K['key'];
}>;

type Values<T> = T[keyof T];

function createEnum<T extends readonly string[], B extends boolean>(arr: T, numeric?: B): Enum<T, B> {
const obj: any = {};
for (const [i, el] of arr.entries()) {
obj[capitalize(el)] = numeric ? i : el;
}
return obj as Enum<T, B>;
}

function capitalize(x: string): string {
return x.charAt(0).toUpperCase() + x.slice(1);
}

const commandItems = [
'echo',
'grep',
'sed',
'awk',
'cut',
'uniq',
'head',
'tail',
'xargs',
'shift',
] as const;

export const Command = createEnum(commandItems, false);
// export const Command = createEnum(commandItems, true);
type Command = Values<typeof Command>;

Best regards,
Marcel

Marcel Büchi  Apr 29, 2024