[TypeScript] Type Challenges #2793 - Mutable

29 阅读1分钟

题目描述

实现一个通用的类型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 Record<string, any>> = {
  -readonly [K in keyof T]: T[K]
}

映射类型

type Mutable<T extends Record<string, any>> = {
  -readonly [P in keyof T]: T[P]
}
  • 类型约束:

    • T extends Record<string, any>:确保T是一个对象类型,其键为字符串,值为任意类型
  • 映射类型:

    • -readonly [P in keyof T]: T[P]

      • -readonly:移除readonly修饰符,使属性变为可变

      • [P in keyof T]:遍历T的所有键

      • T[P]:保留每个键的值类型