跳至主要內容

8. Readonly 2

鸭梨小于 1 分钟

8. Readonly 2

<题目描述>

::: playground#ts 8. Readonly 2

@file index.ts

// ============= Test Cases =============
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>>,
  Expect<Alike<MyReadonly2<Todo2, 'description' >, Expected>>,
]

// @ts-expect-error
type error = MyReadonly2<Todo1, 'title' | 'invalid'>

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
}

// ============= Your Code Here =============
type MyReadonly2<T, K> = any

:::

点击查看答案
type MyReadonly2<T, K extends keyof T = keyof T> = {
  [P in keyof T as P extends K ? never: P]: T[P]
} & {
  readonly [P in K]: T[P]
}