我正在研究type-challenges中的question.
这就是要求:实现一个通用的MyReadonly2<;T、 K>;它接受两个类型参数T和K.
K specify the set of properties of T that should set to Readonly. When K is not provided, it should make all properties readonly just like the normal Readonly. The solution works fine in v4.4+, not in v4.5+.
//solution 1
type MyReadonly2<T, K extends keyof T = keyof T> = T & {
readonly [P in K]: T[P]
}
重现问题:
v4.7.2中的解决方案:here
要解决此问题,请执行以下操作:
// solution 2
type MyReadonly2<T, K extends keyof T = keyof T> = Omit<T, K> & {
readonly [P in K]: T[P]
}
它在V4.7.2中运行良好.here
我就是想不出解决方案1不起作用的原因.