type-challenges:Mutable

78 阅读1分钟

Mutable

问题描述

实现一个通用的类型 Mutable<T>,使类型 T 的全部属性可变(非只读)。

例如:

interface Todo {
  readonly title: string
  readonly description: string
  readonly completed: boolean
}
​
type MutableTodo = Mutable<Todo> // { title: string; description: string; completed: boolean; }
// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'interface Todo1 {
  title: string
  description: string
  completed: boolean
  meta: {
    author: string
  }
}
​
type List = [1, 2, 3]
​
type cases = [Expect<Equal<Mutable<Readonly<Todo1>>, Todo1>>, Expect<Equal<Mutable<Readonly<List>>, List>>]
​
type errors = [
  // @ts-expect-error
  Mutable<'string'>,
  // @ts-expect-error
  Mutable<0>
]
​
// ============= Your Code Here =============
type Mutable<T extends object> = {
  -readonly [P in keyof T]: T[P]
}
​

感觉应该是简单题,只需要去掉修饰符 readonly 即可,当然传入类型的参数也需要约束为对象。很难想象这道题居然是和 MinusOne 一个难度的,区分的有问题吧。