将字符串数组类型缩小为字符串文字的元组时,减少样板

时间:2019-07-17 16:10:49

标签: typescript

我将相同的代码编写了两次。一次输入类型,一次输入值。 如何以一种易于理解的方式减少样板?

type Chart = {
  started: ["count"];
  counting: ["count", "end"];
  ended: ["restart"];
};

const chart: Chart = {
  started: ["count"],
  counting: ["count", "end"],
  ended: ["restart"]
};

注意:as const几乎可以工作,但是添加readonly会使其他类型不匹配,除非基本上所有代码都是用readonly编写的。

这里是一个操场,那里有其他可供选择的灵感来源:https://www.typescriptlang.org/play/index.html#code/PTAEAUCcHsCMBsCmBbAXKALgTwA6IM6iyIDG0yio+GkAlgHYDmA2gLoB0AUGfdaJIngBDAB6IAJgGEAFkMgZQAXlABvTqA1UMcjBPTMARInriDrADTrNx8XtCGB1HWc4BfANycvIUJICukAL0CvjQ8H4YtND06PRyMADumNKU2HiE4tAJ9KAJtBjSoEKYuIhcPgBCEaD5oBRCvLl0kUzJlPhCFMkMjJh5JGWcaZQAcvFZEjI6SqpWGk7ydoY2Zp6aoDZLBo7a8qtunpw+ACrStIQJ0JAA1vhcPHxxgRNSsvLoY88Jk28KymrrBa6cT6IwmMyWdabEH2bYEXYYFwebxgU7nXJXW7mIjVdFCeChUAAN0QkCwxNJsGg+EQ2Ia4iKBOgoCQ+EIDAwfnytBJmGZxwAykREIwGPRSXduNE+CTIFSaVN5DMAZogVsVqwioRluDNZDrCYtjtnJqhNq4UCzKADijQGjCPjkNSFJcbvhsbBqgVKAIhJl6PByTgYHh5LQCLlaPB4HVzsghBgSIU8gU2vx4aBoAAzNNkWz3aUKX3+wOKv6zQEI9W6-UaaGg417VhuLWgB4YQ5AA

1 个答案:

答案 0 :(得分:1)

您可以按照说明使用as const,然后使用映射的类型修饰符从所有属性中删除readonly

const chart = {
  started: ["count"],
  counting: ["count", "end"],
  ended: ["restart"]
} as const;

type ChartReadonly = typeof chart;

// you can use a basic generic to help here.
type Mutable<T> = {
  -readonly[P in keyof T]: T[P];
};

type Chart = Mutable<ChartReadonly>;

// or without generics
type Chart2 = {
  -readonly[P in keyof ChartReadonly]: ChartReadonly[P];
};

// or all at once:
type Chart3 = {
  -readonly[P in keyof typeof chart]: typeof chart[P];
};