【问题标题】:Is it possible to restrict an interface field names according some enum?是否可以根据一些枚举来限制接口字段名称?
【发布时间】:2019-09-17 07:23:03
【问题描述】:

是否可以根据一些枚举来限制接口字段名称(不将枚举的每个值都指向名称)?例如:

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",
}

【问题讨论】:

标签: typescript


【解决方案1】:

我认为使用接口是不可能的。
您可以使用类型获得相同的结果。

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'
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多