前言
简单题:实现Readonly
TS Playground:www.typescriptlang.org/play?#code/…
正文
题目
7 - Readonly
-------
by Anthony Fu (@antfu) #easy #built-in #readonly #object-keys
### Question
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:
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
> View on GitHub: <https://tsch.js.org/7>
/* _____________ Your Code Here _____________ */
type MyReadonly<T> = any
/* _____________ Test Cases _____________ */
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
}
}
答案
type MyReadonly<T> = {
readonly [key in keyof T]: T[key]
};
总结
readonly
readonly
修饰符,首先是一个关键字- 对类中的属性成员进行修饰
- 修饰之后,该属性成员就不能修改,那么这个属性成员就成为类的参数属性
- 只能访问
- 在构造函数中是可以对只读属性进行修改
- 在类的普通方法中不能被修改
class Person {
readonly name: string,
constructor(name: string) {
this.name = name;
}
say() {
console.log(`我的名字叫${this.name}`);
}
}
let person = new Person('Haha');