【问题标题】:User-defined type guards and lodash用户定义的类型保护和 lodash
【发布时间】:2017-02-18 07:53:05
【问题描述】:

我一直在玩 lodash 和 typescript,发现以下内容。

假设您有一个具有以下签名的用户定义类型保护:

isCat(animal: Animal) animal is Cat

您有一个要过滤的动物列表:

let animals: Animal[] = // assume some input here
let cats = _.filter(animals, isCat);

那么类型系统实际上会推断出猫是动物[]类型,而不是猫[]类型。

但是,如果您像这样扩展 lodash 类型(抱歉,我在这里使用链接只是巧合,但您明白了):

interface TypeGuardListIterator<T, TResult extends T> {
    (value: T, index: number, list: List<T>): value is TResult;
}
interface _Chain<T> {
    filter<TResult extends T>(iterator: TypeGuardListIterator<T, TResult>): _Chain<TResult>;
}

那么类型系统实际上会推断cats 变量是Cat[] 类型。这太棒了!也许它应该被添加到这个库的类型中。

问题是:假设您有多种类型的动物,您如何使用 group by 来做到这一点,并且类型推断也能正常工作?

let groupedAnimals = _.groupBy(animals, animal => {
    if (isCat(animal)) {
        return "cats";
    } else if (isDog(animal)) {
        return "dogs";
    } else if (isHorse(animal)) {
        return "horses";
    }
});

理想情况下,groupedAnimals 的类型如下所示:

interface GroupedAnimals {
    cats: Cat[];
    dogs: Dog[];
    horses: Horse[];
}

这甚至可能吗?我觉得这会试图在这里将多个类型保护聚合到一个函数中。从概念上讲,这些类型是有意义的,但我不确定如何实现。

【问题讨论】:

    标签: typescript lodash typescript-typings


    【解决方案1】:

    您不能为此使用类型保护,但还有其他方法可以在类型级别区分类型。

    为了使这成为可能,您必须使用“理解”您试图通过类型级别的返回值区分联合成员的签名来扩充 groupBy。

    对此的常用术语是联合区分,区分联合成员的最常见方法是通过可用于在类型级别和运行时进行区分的静态标记成员。 This post 详细阐述了标记工会和工会歧视的概念。

    为简洁起见,省略 Horse 类型,以下是您的情况:

    import {groupBy} from "lodash";
    
    interface Cat {
        _type: "cat"
    }
    
    
    interface Dog {
        _type: "dog"
    }
    
    
    type Animal = Cat | Dog;
    
    const animals: Animal[] = [];
    
    declare module "lodash" {
        interface LoDashStatic {
            groupBy<T extends Animal>(collection: List<T>, iteratee?: (i: T) => T["_type"]): {
                [K in T["_type"]]: Array<T & {_type: K}>
            };
        }
    }
    
    // Use groupBy
    const group = groupBy(animals, (animal) => animal._type);
    

    如果上面的代码没有意义,您可能需要阅读更多关于mapped types 和module augmentation 的信息。

    推断的组类型将是:

    const group: {
        cat: ((Cat & {
            _type: "cat";
        }) | (Dog & {
            _type: "cat";
        }))[];
        dog: ((Cat & {
            _type: "dog";
        }) | (Dog & {
            _type: "dog";
        }))[];
    }
    

    这实际上是你想要的(因为Dog &amp; {_type: "cat"} 和Cat &amp; {_type: "dog"} 永远不会匹配任何东西),但看起来很难看。

    要稍微清理一下,可以使用鉴别器接口:

    interface AnimalDiscriminator {
        cat: Cat,
        dog: Dog
    }
    

    您可以在 groupBy 签名中映射:

    declare module "lodash" {
        interface LoDashStatic {
            groupBy<T extends Animal>(collection: List<T>, iteratee?: (i: T) => T["_type"]): {
                [K in T["_type"]]: Array<AnimalDiscriminator[K]>
            };
        }
    }
    

    现在组的类型将是:

    const group: {
        cat: Cat[];
        dog: Dog[];
    }
    

    看起来好多了。

    【讨论】:

      猜你喜欢
      • 2019-01-03
      • 2015-12-19
      • 2018-03-26
      • 2021-10-31
      • 1970-01-01
      • 2018-05-30
      • 2016-09-06
      • 2022-01-12
      • 2020-11-11
      相关资源
      最近更新 更多