需求:实现一个MyReadonly,该 Readonly 会接收一个 泛型参数,并返回一个完全一样的类型,只是所有属性都会被 readonly 所修饰。
type MyReadonly<T> = any
import type { Equal, Expect } from '@type-challenges/utils'
type cases = [
Expect<Equal<MyReadonly<Todo1>, Readonly<Todo1>>>,
]
interface Todo1 {
title: string
description: string
completed: boolean
meta: {
author: string
}
}
先用js的思路写一遍:
- 返回一个对象
- 遍历obj(js对象 ts接口)
- 加上readonly关键字
- 通过key来获取obj(接口)里面的值
function MyReadonly(obj){
const result = {};
for(let key in obj){
result['readonly'+key] = obj[key];
}
return result
}
再想想ts怎么写:
- 返回一个对象 √
- 遍历obj(js对象 ts接口)【ts使用in keyof去遍历接口】</