Is it possible to have a function called createFields that takes a generic Object type, such as User, and extracts a subset of keys that can be inferred with a string literal array, similar to the selectable property in Fields? If so, how can this be achieved using TypeScript? Thank you.
Below is the code snippet
interface User {
id: number;
username: string;
password: string;
age: number;
}
interface Fields<T extends object = {}> {
selectable: Array<keyof T>;
sortable: Array<keyof T>;
}
function createFields<T extends object = {}>({ selectable, sortable }: Fields<T>) {
return {
// How can I retrieve the type of selectable as ("id" | "username" | "age")[]
select(fields: typeof selectable): string {
return fields.join(',')
}
}
}
const UserFields: Fields<User> = {
selectable: ['id', 'username', 'age'],
sortable: ['username', 'age']
}
const fields = createFields(UserFields)
// current output
// => fields.select = (fields: ("id" | "username" | "password" | "age")[]): string;
// expected output
// => fields.select = (fields: ("id" | "username" | "age")[]): string;