TypeScript 类型体操 —— Readonly 2

99 阅读1分钟

题目地址

实现

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

使用

type example = {
    name: string,
    age: string,
    address: string
}

type example2 = MyReadonly2<example, 'age'>
const o: example2 = {
    name: '111',
    age: '2222',
    address: '222'
}
o.address = '333'
o.name = '1'
o.age = '222' // 报错,Cannot assign to 'age' because it is a read-only property.