We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现一个通用MyReadonly2<T, K>,它带有两种类型的参数T和K。 K指定应设置为Readonly的T的属性集。如果未提供K,则应使所有属性都变为只读,就像普通的Readonly<T>一样。
MyReadonly2<T, K>
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
The text was updated successfully, but these errors were encountered:
//实现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]; };
Sorry, something went wrong.
No branches or pull requests
实现一个通用
MyReadonly2<T, K>
,它带有两种类型的参数T
和K
。K
指定应设置为Readonly的T
的属性集。如果未提供K
,则应使所有属性都变为只读,就像普通的Readonly<T>
一样。The text was updated successfully, but these errors were encountered: