Back to Type Challenges

README.Zh CN

questions/00008-medium-readonly-2/README.zh-CN.md

latest3.0 KB
Original Source
<!--info-header-start--><h1>对象部分属性只读 </h1><blockquote><p>by Anthony Fu <a href="https://github.com/antfu" target="_blank">@antfu</a></p></blockquote><p><a href="https://tsch.js.org/8/play/zh-CN" target="_blank"></a> &nbsp;&nbsp;&nbsp;<a href="./README.md" target="_blank"></a> <a href="./README.ja.md" target="_blank"></a> <a href="./README.ko.md" target="_blank"></a> <a href="./README.pt-BR.md" target="_blank"></a> </p><!--info-header-end-->

实现一个泛型MyReadonly2<T, K>,它带有两种类型的参数TK

类型 K 指定 T 中要被设置为只读 (readonly) 的属性。如果未提供K,则应使所有属性都变为只读,就像普通的Readonly<T>一样。

例如

ts
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
<!--info-footer-start-->

<a href="../../README.zh-CN.md" target="_blank"></a> <a href="https://tsch.js.org/8/answer/zh-CN" target="_blank"></a> <a href="https://tsch.js.org/8/solutions" target="_blank"></a> <hr><h3>相关挑战</h3><a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00007-easy-readonly/README.zh-CN.md" target="_blank"></a> <a href="https://github.com/type-challenges/type-challenges/blob/main/questions/00009-medium-deep-readonly/README.zh-CN.md" target="_blank"></a> <!--info-footer-end-->