0

Is it possible to restrict an interface field names according some enum (without pointing each value of enum as name)? For example:

enum childSumNames {
    child_incoming_costs = "isv_child_incoming_costs",
    child_est_revenue = "isv_child_est_revenue",
    child_margin = "isv_child_margin",
}

/** Only field names from childSumNames enum are allowed */
interface IChildSumFieldMapper {
    [key in childSumNames]: string // something like this (but it is incorrect syntax)...

    /* instead of this:
     * [childSumNames.child_incoming_costs]: string,
     * [childSumNames.child_est_revenue]: string,
     * [childSumNames.child_margin]: string, */
}

// The example of IChildSumFieldMapper instance
const item: IChildSumFieldMapper = {
    [childSumNames.child_incoming_costs]: "isv_incomingcost",
    [childSumNames.child_est_revenue]: "isv_estimatedrevenue",
    [childSumNames.child_margin]: "isv_margin",
}

enter image description here

Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182
  • Possible duplicate of [How to use enum as index key type in typescript?](https://stackoverflow.com/questions/52700659/how-to-use-enum-as-index-key-type-in-typescript) – Harun Yilmaz Sep 17 '19 at 07:29
  • @HarunYilmaz thank you. I updated my code but it is invalid still. I added the screen also. – Andrey Bushman Sep 17 '19 at 07:35

1 Answers1

0

I do not think that this is possible using interfaces.
You can achieve the same result using types.

enum ChildSumNames {
    child_incoming_costs = 'isv_child_incoming_costs',
    child_est_revenue = 'isv_child_est_revenue',
    child_margin = 'isv_child_margin'
}

type ChildSumFieldMapper = {
    [K in keyof typeof ChildSumNames]: string;
};

const map: Partial<ChildSumFieldMapper> = {
    child_est_revenue: 'a',
    child_incoming_costs: 'b',
    child_margin: 'c'
};
Artem Bozhko
  • 1,744
  • 11
  • 12