# Easy - Readonly
# question
Implement the built-in Readonly<T>
generic without using it.
不要使用内置的 Readonly<T>
,自己实现一个。
Constructs a type with all properties of T
set to readonly, meaning the properties of the constructed type cannot be reassigned.
该 Readonly
会接收一个泛型参数 T
,并返回一个完全一样的类型,只是所有属性都会被 readonly
所修饰。也就是不可以再对该对象的属性赋值。
For example:
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
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# answer
type MyReadonly<T> = {
readonly [P in keyof T]: T[P]
}
1
2
3
2
3