[Typescript] 87. Medium - DeepMutable
typescript Medium 87
2023-09-14 09:00:44 时间
Implement a generic DeepMutable which make every parameter of an object - and its sub-objects recursively - mutable.
For example
type X = {
readonly a: () => 1
readonly b: string
readonly c: {
readonly d: boolean
readonly e: {
readonly g: {
readonly h: {
readonly i: true
readonly j: "s"
}
readonly k: "hello"
}
}
}
}
type Expected = {
a: () => 1
b: string
c: {
d: boolean
e: {
g: {
h: {
i: true
j: "s"
}
k: "hello"
}
}
}
}
type Todo = DeepMutable<X> // should be same as `Expected`
You can assume that we are only dealing with Objects in this challenge. Arrays, Functions, Classes and so on do not need to be taken into consideration. However, you can still challenge yourself by covering as many different cases as possible.
/* _____________ Your Code Here _____________ */
type DeepMutable<T extends Record<PropertyKey,any>> = T extends (...args: any[]) => any
? T
: {
- readonly [K in keyof T] : DeepMutable<T[K]>
};
type x = DeepMutable<Test2>
/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'
interface Test1 {
readonly title: string
readonly description: string
readonly completed: boolean
readonly meta: {
readonly author: string
}
}
type Test2 = {
readonly a: () => 1
readonly b: string
readonly c: {
readonly d: boolean
readonly e: {
readonly g: {
readonly h: {
readonly i: true
readonly j: 's'
}
readonly k: 'hello'
}
readonly l: readonly [
'hi',
{
readonly m: readonly ['hey']
},
]
}
}
}
interface DeepMutableTest1 {
title: string
description: string
completed: boolean
meta: {
author: string
}
}
type DeepMutableTest2 = {
a: () => 1
b: string
c: {
d: boolean
e: {
g: {
h: {
i: true
j: 's'
}
k: 'hello'
}
l: [
'hi',
{
m: ['hey']
},
]
}
}
}
type cases = [
Expect<Equal<DeepMutable<Test1>, DeepMutableTest1>>,
Expect<Equal<DeepMutable<Test2>, DeepMutableTest2>>,
]
type errors = [
// @ts-expect-error
DeepMutable<'string'>,
// @ts-expect-error
DeepMutable<0>,
]
相关文章
- typescript 中使用 setTimeout 返回值类型 eslint 检查错误 ‘NodeJS‘ is not defined.eslint(no-undef)
- 深入浅出 TypeScript
- typescript 接口_typeScript
- ESLint: Typescript + React + TSX 集成
- 【TypeScript】的安装方式
- 简单的贪吃蛇小游戏—TypeScript练习
- Typescript 4.9重点特性探索
- Vue 3 + Typescript + Vite 基个人网站二维码登录功能
- TypeScript泛型应用
- 推荐一个可无限制阅读medium上付费文章的插件-Medium Unlimited