typescript递归类型的终点
来源:11-57 【泛型递归+复杂泛型 交叉类型 综合实战】 跨越式的提高复杂泛型运用能力

crazyones110
2021-09-23
interface Teacher {
name: string;
age: number;
address: {
city: string;
}
}
type ReadOnlyRecursive<T> = {
// 这里不是很能理解, 比如说传进去Teacher, P是name, 值类型就是ReadOnlyRecursive<Teacher["name"]>
// 即ReadOnlyRecursive<string>, 即
/*
{
[P in keyof string]: ReadOnlyRecursive<string[P]>
}
*/
// 但是实际上ReadOnlyRecursive<string> 就是string
[P in keyof T]: ReadOnlyRecursive<T[P]>;
}
一般来说递归是要有一个边界条件的, 这里的边界条件感觉很模糊
2回答
-
keviny79
2021-09-24
// 你找的这个例子不能说明递归的边界
// 老师给你举一个例子:稍复杂: 基于Vue3 Ref响应式对象的递归
interface Ref<T = any> {
value: T
}
type BaseTypes = string | number | boolean
// 判断是否是Ref 类型
type UnwrapRef<T> = T extends Ref<infer V> ? UnWrapSimple<V> :
UnWrapSimple<T>
// 第一行的 ?后面的 T 为递归出口 第二行 :后满的 T为递归出口(就是你说的边界)
// UnwrapRef<T[P]>递归
type UnWrapSimple<T> = T extends Function | BaseTypes | Ref ? T :
T extends object ? { [P in keyof T]: UnwrapRef<T[P]> } : T
let shopCartValue: UnwrapRef<Ref<string>>// 递归出口后的值为 string
let dynamicProxy: UnwrapRef<Ref<string>>
let threadPool: UnwrapRef<Ref<Ref<string>>> = { value: "abc" }// 递归出口为 Ref<string >
let threadPool2: UnwrapRef<Ref<{
thread1: Ref<string>,
thread2: Ref<string>
}>>
122021-09-24 -
keviny79
2021-09-24
// typescript 对底层类型,比如 string ,number 在泛型中的代入会直接完整返回,
// 我提供解决方案如截图:具体还可以再提取出来一次,你可以试下,结果SUCCESS了
00
相似问题