跳到主要内容

Mutable

介绍

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

ts
interface Todo {
readonly title: string
readonly description: string
readonly completed: boolean
}
type MutableTodo = Mutable<Todo> // { title: string; description: string; completed: boolean; }
ts
interface Todo {
readonly title: string
readonly description: string
readonly completed: boolean
}
type MutableTodo = Mutable<Todo> // { title: string; description: string; completed: boolean; }
View on GitHub

起点

ts
/* _____________ Your Code Here _____________ */
 
type Mutable<T> = any
 
/* _____________ Test Cases _____________ */
 
interface Todo1 {
title: string
description: string
completed: boolean
meta: {
author: string
}
}
 
type List = [1, 2, 3]
 
type cases = [
Expect<Equal<Mutable<Readonly<Todo1>>, Todo1>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Mutable<Readonly<List>>, List>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
ts
/* _____________ Your Code Here _____________ */
 
type Mutable<T> = any
 
/* _____________ Test Cases _____________ */
 
interface Todo1 {
title: string
description: string
completed: boolean
meta: {
author: string
}
}
 
type List = [1, 2, 3]
 
type cases = [
Expect<Equal<Mutable<Readonly<Todo1>>, Todo1>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
Expect<Equal<Mutable<Readonly<List>>, List>>,
Type 'false' does not satisfy the constraint 'true'.2344Type 'false' does not satisfy the constraint 'true'.
]
 
take the challenge

解决方案

Spoiler warning // Click to reveal answer
ts
// most popular
 
type Mutable<T> = {
-readonly [K in keyof T]:T[K]
}
 
ts
// most popular
 
type Mutable<T> = {
-readonly [K in keyof T]:T[K]
}
 
view more solutions