Problem
I would like to create a type to set up a type to get the union of all possible constant of a field values for a given array of class instances.
Example
Let's use this code to illustrate what I need.
specific.columns.config.ts
export const SPECIFIC_COLUMNS_CONFIG = [
new ColumnConfig(
{
field: NAME_FIELD,
isEditable: true,
...
}
),
new ColumnConfig(
{
field: STATUS_FIELD,
isEditable: false,
...
}
),
...
] as const;
column.config.ts
class ColumnConfig {
field: string;
isEditable: boolean = false;
...
constructor(partial: Partial<ColumnConfig>){
Object.assign(this, partial)
}
}
field.config.ts
export const NAME_FIELD = "name" as const; // these fields can be used in multiple column configs
export const STATUS_FIELD = "status" as const;
...
Here is what I want to have:
Expected result
type SpecificFields = NAME_FIELD | STATUS_FIELD | ...
What I've tried
I've found a great blog article: https://steveholgado.com/typescript-types-from-arrays/
But unfortunately, it works with raw object (and not class instances):
type SpecificFields = typeof SPECIFIC_COLUMNS_CONFIG[number]["field"] // type SpecificFields = string;
An alternative solution I found is to hard-code all the different values in a constant likewise and extends ColumnConfig:
const SPECIFIC_FIELDS = [ NAME_FIELD, STATUS_FIELD, ... ]
class SpecificColumnConfig extends ColumnConfig {
field: typeof SPECIFIC_FIELDS;
constructor(partial: Partial<SpecificColumnConfig>) {
super(partial);
}
}
But the disadvantage with this solution is that we have to manually add the fields every time we define a new ColumnConfig and I wonder if there was a more effortless solution.
Thanks in advance for your answers !