Imagine having an enum declared as follows:
enum CustomerType {
New = 'new',
Owner = 'self',
Loyal = 'subscriber'
}
Utilizing this enum can simplify checks like:
if(customer.type === CustomerType.New)
What is the recommended approach for typing an object where the enum values serve as keys? For instance, let's consider a function named getCustomerType
that might produce:
{
new: true,
self: false,
subscriber: false
}
Keep in mind that reducing this output to just the true key may not be feasible due to the system's architecture limitations :)
One solution I attempted is as follows:
type CustomerConfig = { [key in CustomerType]: boolean }
Suppose I wish to extract the first true key from this object, the process would look something like this:
export const getCustomer = (obj: CustomerConfig): CustomerType => {
const customerType = Object.keys(obj).find(x => {
// Object.keys return `string[]` instead of keyof type https://github.com/microsoft/TypeScript/issues/20853
return obj[x as keyof CustomerConfig]
})
return customerType as CustomerType
}
const tempCustomer = getCustomer({
'new': true,
'self': false,
'subscriber': false
})
console.log(tempCustomer === CustomerType.New) // true
console.log(tempCustomer === CustomerType.Owner) //false
Is there a more efficient way to achieve this?