我将相同的代码编写了两次。一次输入类型,一次输入值。 如何以一种易于理解的方式减少样板?
type Chart = {
started: ["count"];
counting: ["count", "end"];
ended: ["restart"];
};
const chart: Chart = {
started: ["count"],
counting: ["count", "end"],
ended: ["restart"]
};
注意:as const
几乎可以工作,但是添加readonly
会使其他类型不匹配,除非基本上所有代码都是用readonly
编写的。
答案 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];
};