测试case
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
}
}
- template.ts
type MyReadonly<T> = any
相关知识点
- keyof T
获取 T 接口的所有的key(联合类型)
interface A {
a: 1,
b: 2
}
keyof A // 'a' | 'b'
- in keyof T
遍历生成每一个 T 的key
interface A {
a: 1,
b: 2
}
type r = {
[P in keyof T]: T[P]
}
// 等价于
type r = {
a: number
b: number
}
js 实现
const myReadonly = (obj) => {
const result = {}
for (let key in obj) {
result[`readonly${key}`] = obj[key]
}
return result
}
步骤:
- 返回一个对象
- 遍历obj (js 指的是对象,ts 指的是接口)
- 加上 readonly 前缀
- 通过 key 来获取 obj 的值
ts 实现
//1. = {}
//2. [P in keyof T]
//3. readonly [P in keyof T]
//4. T[P]
type MyReadonly<T> = {
readonly [P in keyof T]: T[P]
}
网友评论