已开机,快来 Type-Challenges【 easy-7-readonly】

185 阅读1分钟

Readonly

实现内置的Readonly<T>,使T的所有属性只读。

例如

interface Todo {
  title: string
  description: string
}
​
const todo: MyReadonly<Todo> = {
  title: "Hey",
  description: "foobar"
}
​
todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property

解答

type Readonly<T> = {
  readonly [P in keyof T]: T[P]
}

测试

type Expect<T extends true> = T;
type Equal<X, Y> = (<T>() => T extends X ? 1 : 2) extends (<T>() => T extends Y ? 1 : 2) ? true : false;

type cases = [
  Expect<Equal<MyReadonly<Todo1>, Readonly<Todo1>>>,
]

interface Todo1 {
  title: string
  description: string
  completed: boolean
  meta: {
    author: string
  }
}

更多解答

分享你的解答 查看解答