使用对象道具作为TS中另一个对象的键

时间:2019-10-31 04:33:31

标签: typescript types typescript-typings

我正在尝试导出具有有效类型的对象并基于该对象创建类型。它按预期工作。这里的问题是Option接口不接受对象键作为键名,即使它们是字符串也是如此。

export const SortValues = {
  NEWER: 'NEWER',
  OLDER: 'OLDER',
  NAME_ASC: 'NAME_ASC',
  NAME_DESC: 'NAME_DESC',
}

interface Option<T = string> {
  key: T;
  value: string;
}

type SortValuesType = keyof typeof SortValues;

// type SortValuesType = 'NEWER' | 'OLDER' | 'NAME_ASC' | 'NAME_DESC'; // This also doesn't work.

export const options: Array<Option<SortValuesType>> = [
  { key: SortValues.NEWER, value: 'Mais novos' },
  { key: SortValues.OLDER, value: 'Mais antigos' },
  { key: SortValues.NAME_ASC, value: 'A - Z' },
  { key: SortValues.NAME_DESC, value: 'Z - A' },
];

我在选项的关键道具上遇到错误"Type 'string' is not assignable to type '"NEWER" | "OLDER" | "NAME_ASC" | "NAME_DESC"'."

此外,如果我将SortValues定义为枚举也可以使用,但是这给我带来了其他问题,因此我需要将其导出为对象。

这是一个片段 https://codesandbox.io/s/fqide

1 个答案:

答案 0 :(得分:0)

您需要使用jtf.addActionListener(new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { try { jtf.setText(" "); //Simulated backspace to delete space Robot robot = new Robot(); int backspace = KeyEvent.VK_BACK_SPACE; robot.keyPress(backspace); robot.keyRelease(backspace); } catch (AWTException ex) { ex.printStackTrace(); } } }); 断言。即使在const定义中,属性值也会扩大,因此as const的类型将是NEWER,而不是字符串文字类型string'NEWER'将指示编译器保留字符串文字类型

as const

PLAY