I have an instance of my db user model and an array with a list of an object properties:
interface User = {
firstName: string,
lastName: string,
isActive: boolean,
phone: string,
// and a lot of other extra properties omitted here
}
const selectedFields = ['firstName', 'lastName'];
I'm trying to use typescript generics to build a new type with the original class and only the selected properties:
const selectedUserInterface = {
firstName: string,
lastName: string,
}
I know I can use "as const" like described here ( TypeScript: Define a union type from an array of strings )
const fruits = ["Apple", "Orange", "Pear"] as const;
type Fruit = typeof fruits[number]; // "Apple" | "Orange" | "Pear"
But what I want is to write a generic type, something like an utility type, that return the same without using "as const" and without repeating "typeof ....".
I tried this but it's not working:
type SelectProps<T extends object, K extends (keyof T) & string[]> = Pick<T, K>;
As a stepback (just to obtain literal type from array) I tried this, but can't understand why it's not working
type ArrayToUnion<T extends readonly any[]> = typeof T[number];
Can anyone explain and guide me to the solution?