我一直在研究 lodash 和 typescript,并发现了以下内容。
假设您有一个具有以下签名的用户定义类型保护:
isCat(animal: Animal) animal is Cat
并且您有一个要过滤的动物列表:
let animals: Animal[] = // assume some input here
let cats = _.filter(animals, isCat);
那么类型系统实际上会推断猫是 Animal[] 类型,而不是 Cat[] 类型。
但是,如果你像这样扩展 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[] 类型。这太棒了!也许应该将其添加到该库的类型中。
问题是:假设您有多种类型的动物,您如何使用分组依据执行此操作,并使类型推断正常工作?
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[];
}
这可能吗?我觉得这会试图在这里将多种类型的守卫聚合到一个函数中。从概念上讲,这些类型是有意义的,但我不确定如何实现。
最佳答案
你不能为此使用类型保护,但还有其他方法可以在类型级别区分类型。
为了使这成为可能,您必须使用一个签名来扩充 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 & {_type: "cat"}
和 Cat & {_type: "dog"}
永远不会匹配任何东西),但看起来很丑。
要稍微清理一下,您可以使用鉴别器接口(interface):
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[];
}
看起来好多了。
关于typescript - 用户定义的类型保护和 lodash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42312640/