李恒道 发表于 2022-7-18 00:31:40

typescript类型体操记录贴(三)Readonly

地址
https://github.com/type-challenges/type-challenges/blob/main/questions/00007-easy-readonly/README.md
# Readonly
```
Implement the built-in Readonly<T> generic without using it.

Constructs a type with all properties of T set to readonly, meaning the properties of the constructed type cannot be reassigned.

For example:
```
实现内置Readonly泛型而不使用他
构建一个类型将T的所有属性设置成只读,意味着所有属性之恩给你构建类型不能去重新设置
例如
```
interface Todo {
title: string
description: string
}

const todo: MyReadonly<Todo> = {
title: "Hey",
description: "foobar"
}

todo.title = "Hello" // Error: cannot reassign a readonly property
todo.description = "barFoo" // Error: cannot reassign a readonly property
```
这题跟二差不多
基本白给题
直接K in keyof T
遍历T的所有属性,然后加一个readonly即可
上代码
```
type MyReadonly<T> = {
readonly :T
}
```
搞定
![图片.png](data/attachment/forum/202207/18/003136rq1cnuqmwul1cwcn.png)
页: [1]
查看完整版本: typescript类型体操记录贴(三)Readonly