Typescript类型体操 – Mutable

2023-03-19 17:50

题目

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

例如:

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

English

Implement the generic Mutable<T> which makes all properties in T mutable (not readonly).

For example

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

答案

type Mutable<T extends object> = { -readonly [K in keyof T]: T[K] };

在线演示

作者:Laggage

出处:https://www.cnblogs.com/laggage/p/type-challenge-mutable.html

说明:转载请注明来源