8000 GitHub · Where software is built
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
5. MyReadonly #9
Open
Open
@astak16

Description

@astak16

题目

题目链接:MyReadonly

实现 Readonly 使得属性变为可读。

当尝试修改 titledescription 会报错

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

答案

方法一

type MyReadOnly<T extends {}> = { readonly [key in keyof T]: T[key] };

知识点

  1. 使用 keyofT 中的属性变成联合类型
  2. 使用 in 遍历联合类型
  3. 最后用 readonly 去修饰每一个 key

方法二

type MyReadonly<T, K extends keyof T = keyof T> = {
  readonly [key in K]: T[key];
};

知识点

这里做了两次约束

  1. 第一个约束是 K extends keyof TKT 属性的联合类型
  2. 第二个约束是 = keyof T ,如果没有为该类型指定类型参数,默认使用 keyof T

基础知识

  1. 默认约束 = keyof T

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0