代码之家  ›  专栏  ›  技术社区  ›  Kyung Lee

为什么在传递给条件类型时,联合字符串泛型类型被视为特定的文字?

  •  1
  • Kyung Lee  · 技术社区  · 7 月前

    打字版本:5.6.2

    为什么 ApprovalType 被篡改为特定值 批准类型 如果函数参数类型是条件类型,即使我显式传递泛型参数 <ApprovalType> 调用函数时?

    Playground

    type ApprovalType = "PENDING" | "APPROVED" | "REJECTED";
    
    type A<T> = {
        options: T[];
    };
    
    type B<T> = {
        options: T[];
    };
    
    function conditionalTypeFn<T>(props: T extends string ? B<T> : A<T>) {
        return props;
    }
    conditionalTypeFn<ApprovalType>({
        /**
         * ❌ Type '("PENDING" | "APPROVED" | "REJECTED")[]' is not assignable
         * to type '"PENDING"[] | "APPROVED"[] | "REJECTED"[]'
         */
        options: ["PENDING", "APPROVED", "REJECTED"],
    });
    
    function unionTypeFn<T>(props: A<T> | B<T>) {
        return props;
    }
    unionTypeFn<ApprovalType>({
        /* ✅ no error */
        options: ["PENDING", "APPROVED", "REJECTED"],
    });
    
    1 回复  |  直到 7 月前
        1
  •  1
  •   Robby Cornelissen    7 月前

    默认情况下,如中所述 documentation ,条件类型在 分配的 在联合类型上使用时的方式。

    这里有一个简化的例子来证明这一点:

    type ApprovalType = "PENDING" | "APPROVED" | "REJECTED";
    
    type Distributed<T> = T extends string ? T[] : never;
    
    type ApprovalTypes = Distributed<ApprovalType>;
    // type ApprovalTypes = "PENDING"[] | "APPROVED"[] | "REJECTED"[]
    

    为了避免分布式行为,您可以在条件类型中使用方括号。应用于同一个例子,这将产生:

    type ApprovalType = "PENDING" | "APPROVED" | "REJECTED";
    
    type NonDistributed<T> = [T] extends [string] ? T[] : never;
    
    type ApprovalTypes = NonDistributed<ApprovalType>;
    // type ApprovalTypes = ("PENDING" | "APPROVED" | "REJECTED")[]
    

    或者,应用于您问题中的代码:

    function conditionalTypeFn<T>(props: [T] extends [string] ? B<T> : A<T>) {
        return props;
    }
    

    Playground link

    推荐文章