是否可以根据一些枚举来限制接口字段名称?

时间:2019-09-17 07:23:03

标签: typescript

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

import React from "react";
import ReactDOM from "react-dom";
import { Select } from "antd";

import "./styles.css";

const { Option } = Select;
const test = [
  { id: 1, name: "test1", value: { x: 10 } },
  { id: 2, name: "test2", value: { x: 11 } },
  { id: 3, name: "test3", value: { x: 12 } }
];

class App extends React.Component {
  handleChange = id => {
    const clickedOption = test.find(item => item.id === id);
    const value = `${clickedOption.id}, ${clickedOption.value.x}`;
    console.log(value);
  };
  render() {
    return (
      <div className="App">
        <Select
          onChange={this.handleChange}
          style={{ width: 200 }}
          placeholder="Select a person"
          optionFilterProp="children"
        >
          {test.map((item, index) => (
            <Option value={item.id} key={index}>
              {item.name}
            </Option>
          ))}
        </Select>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

enter image description here

1 个答案:

答案 0 :(得分:0)

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

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