The & string
is utilized to filter out any keys of the object that are not strings, eliminating numbers and symbols. While your Product
type doesn't include these, other objects might.
For instance:
const foo = Symbol();
type Product = {
name: string;
price: number;
[3]: boolean;
[foo]: string;
}
type KeysWithoutString<T> = keyof T;
type KeysWithString<T> = keyof T & string
const example1: KeysWithoutString<Product> = 'name';
const example2: KeysWithoutString<Product> = 'price';
const example3: KeysWithoutString<Product> = 'error'; // Error (not a key)
const example4: KeysWithoutString<Product> = 3; // Allow
const example5: KeysWithoutString<Product> = foo; // Allowed
const example6: KeysWithString<Product> = 'name';
const example7: KeysWithString<Product> = 'price';
const example8: KeysWithString<Product> = 'error'; // Error (not a key)
const example9: KeysWithString<Product> = 3; // Error (a key, but not a string)
const example10: KeysWithString<Product> = foo; // Error (a key, but not a string)
Playground Link