Skip to content

12. MyReadonly2 #17

@astak16

Description

@astak16

题目

题目链接:MyReadonly2

实现 MyReadonly2 ,接收两个参数,把第二个参数变为只读,同时第二个参数可以不传,不传的话就把第一个参数中所有的属性都变位只读。

import type { Alike, Expect } from "@type-challenges/utils";

type cases = [
  Expect<Alike<MyReadonly2<Todo1>, Readonly<Todo1>>>,
  Expect<Alike<MyReadonly2<Todo1, "title" | "description">, Expected>>,
  Expect<Alike<MyReadonly2<Todo2, "title" | "description">, Expected>>
];

interface Todo1 {
  title: string;
  description?: string;
  completed: boolean;
}

interface Todo2 {
  readonly title: string;
  description?: string;
  completed: boolean;
}

interface Expected {
  readonly title: string;
  readonly description?: string;
  completed: boolean;
}

答案

实现 MyReadonly2 类型,把 T 变位只读,用 OmitT 中挑选出 K,最后使用 & 连接

方法一

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

方法二

type MyReadonly2<T, K extends keyof T = keyof T> = {
  readonly [key in K]: T[key];
} & {
  [key in K as key extends K ? key : never]: T[key];
};

方法三

type MyReadonly2<T, K extends keyof T = keyof T> = Readonly<T> & Omit<T, K>;

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions