2 个回答

这个真的会

泛型中的含义:T 约束为 Paths 的 key,U 约束为 Paths 的值

等号后面:为条件类型。如果 T 的类型为 Paths 的 key,则返回是 Paths 的 key 为 T 的值,的类型

涉及到知识点,类型约束、获取类型的 key 的联合类型、条件类型

举个例子:

interface Paths {
    PathItem1: {
        a: string;
        b: number;
    };
    PathItem2: {
        c: boolean;
        d: number;
    };
}

type UrlType<T extends keyof Paths, U extends keyof Paths[T]> = Paths[T][U];

type A = UrlType<'PathItem2', 'c'>; // A -> boolean
type B = UrlType<'PathItem1', 'a'>; // B -> string

当UrlType的第一个泛型,即T传入'PathItem2'的时候, U的约束则为 keyof Paths['PathItem2'], 也就是 'c' | 'd'
Paths[T]则为 Path['PathItem2']

{
    c: boolean;
    d: number;
};

当第二个泛型传入'c'时 Paths[T] [U]则为 Paths['PathItem2'] ['c'] 也就是boolean

另外我认为这段代码是无意义的代码
T extends keyof Paths ? Paths[T] [U] : any
因为T已经做过了泛型约束, 所以传入的T必然是keyof Paths这个联合类型中的一个值, 如果不是的话,在传入T的时候TS会报错

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题