Look at the code snippet provided below.
interface IEmployee {
ID: string
Employee: string
Phone: number
Town: string
Email: string
Name: string
}
// Retrieve all properties of type IEmployee
let allProps = findSpecificItem<IEmployee>("ID = 1234234")
// Select only specific properties like Email and Phone from IEmployee
let picked = findSpecificItem<IEmployee>("ID = 1234234", ["Email", "Phone"])
How would you define the function findSpecificItem
? Is it possible to maintain compatibility with the existing calling code?
Possible approaches
Using arrays (Not recommended, does not work)
The following implementation is not functional as typeof fields[number]
will result in Array<keyof T>
function findSpecificItem<T>(filter: string, fields: Array<keyof T> =[]): Pick<T,typeof fields[number]> {
return db.select(filter, fields)
}
Introducing a second generic parameter (Effective approach)
This method works but might be less straightforward to understand
function select<T, K extends Partial<T> = T>(filter: string, fields = Array<keyof K>): K {
return db.select(filter, fields)
}
const props = ["Email", "Phone"] as const
type propsType = Pick<IEmployee, typeof props[number]>
let allProps = select<IEmployee>("Employee: 1234234")
let picked = select<IEmployee, propsType>("Employee: 1234234")