Typescript类型体操 - Deep Readonly
作者:互联网
题目
中文
实现一个通用的DeepReadonly<T>
,它将对象的每个参数及其子对象递归地设为只读。
您可以假设在此挑战中我们仅处理对象。数组,函数,类等都无需考虑。但是,您仍然可以通过覆盖尽可能多的不同案例来挑战自己。
例如
type X = {
x: {
a: 1
b: 'hi'
}
y: 'hey'
}
type Expected = {
readonly x: {
readonly a: 1
readonly b: 'hi'
}
readonly y: 'hey'
}
type Todo = DeepReadonly<X> // should be same as `Expected`
English
Implement a generic DeepReadonly<T>
which make every parameter of an object - and its sub-objects recursively - readonly.
You can assume that we are only dealing with Objects in this challenge. Arrays, Functions, Classes and so on do not need to be taken into consideration. However, you can still challenge yourself by covering as many different cases as possible.
For example:
type X = {
x: {
a: 1
b: 'hi'
}
y: 'hey'
}
type Expected = {
readonly x: {
readonly a: 1
readonly b: 'hi'
}
readonly y: 'hey'
}
type Todo = DeepReadonly<X> // should be same as `Expected`
答案
type DeepReadonly<T extends {}> = { readonly [P in keyof T]: T[P] extends { [K: string]: {} } | any[] ? DeepReadonly<T[P]> : T[P] };
标签:Typescript,DeepReadonly,readonly,Deep,hey,Readonly,hi,Expected,type 来源: https://www.cnblogs.com/laggage/p/type-challenge-deep-readonly.html