Ts体操--myReadonly2
zhuba-Ahhh opened this issue · comments
实现一个通用MyReadonly2<T, K>
,它带有两种类型的参数T
和K
。
K
指定应设置为Readonly的T
的属性集。如果未提供K
,则应使所有属性都变为只读,就像普通的Readonly<T>
一样。
type MyReadonly2<T, K extends keyof T = keyof T> = {
readonly [P in K]: T[P];
} & {
[P in keyof T as P extends K ? never : P]: T[P];
};
interface Todo {
title: string
description: string
completed: boolean
}
const todo: MyReadonly2<Todo, 'title' | 'description'> = {
title: "Hey",
description: "foobar",
completed: false,
}
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
todo.completed = true // OK
//实现1,使用内置Exclude
type MyReadonly2<T, K extends keyof T = keyof T> = {
readonly [P in K]: T[P];
} & {
[P in Exclude<keyof T, K>]: T[P];
};
//实现2 ,完全手写
type MyExclude<T, K> = T extends K ? never : T;
type MyReadonly2<T, K extends keyof T = keyof T> = {
readonly [P in K]: T[P];
} & {
[P in MyExclude<keyof T, K>]: T[P];
};