我的目标是编写谓词函数(isNull
and isUndefined
例如)在 TypeScript 中满足以下条件:
- 可以独立使用:
array.filter(isNull)
- 可以逻辑组合:
array.filter(and(not(isNull), not(isUndefined)))
- 使用类型保护,因此 TypeScript 知道例如的返回类型
array.filter(isNull)
将null[]
- 组合谓词可以提取到新的谓词函数中,而不会破坏类型推断:
const isNotNull = not(isNull)
前两个条件很容易满足:
type Predicate = (i: any) => boolean;
const and = (p1: Predicate, p2: Predicate) =>
(i: any) => p1(i) && p2(i);
const or = (p1: Predicate, p2: Predicate) =>
(i: any) => p1(i) || p2(i);
const not = (p: Predicate) =>
(i: any) => !p(i);
const isNull = (i: any) =>
i === null;
const isUndefined = (i: any) =>
i === undefined;
const items = [ "foo", null, 123, undefined, true ];
const filtered = items.filter(and(not(isNull), not(isUndefined)));
console.log(filtered);
但因为这里没有使用类型保护,TypeScript 假设变量filtered
具有相同的类型items
这是(string,number,boolean,null,undefined)[]
虽然现在实际上应该是(string,number,boolean)[]
.
所以我添加了一些打字稿魔法:
type Diff<T, U> = T extends U ? never : T;
type Predicate<I, O extends I> = (i: I) => i is O;
const and = <I, O1 extends I, O2 extends I>(p1: Predicate<I, O1>, p2: Predicate<I, O2>) =>
(i: I): i is (O1 & O2) => p1(i) && p2(i);
const or = <I, O1 extends I, O2 extends I>(p1: Predicate<I, O1>, p2: Predicate<I, O2>) =>
(i: I): i is (O1 | O2) => p1(i) || p2(i);
const not = <I, O extends I>(p: Predicate<I, O>) =>
(i: I): i is (Diff<I, O>) => !p(i);
const isNull = <I>(i: I | null): i is null =>
i === null;
const isUndefined = <I>(i: I | undefined): i is undefined =>
i === undefined;
现在看来有效了filtered
被正确地简化为类型(string,number,boolean)[]
.
但是因为not(isNull)
可能会经常使用我想将其提取到一个新的谓词函数中:
const isNotNull = not(isNull);
虽然这在运行时完美工作,但不幸的是它无法编译(启用严格模式的 TypeScript 3.3.3):
Argument of type '<I>(i: I | null) => i is null' is not assignable to parameter of type 'Predicate<{}, {}>'.
Type predicate 'i is null' is not assignable to 'i is {}'.
Type 'null' is not assignable to type '{}'.ts(2345)
所以我想在使用谓词作为数组的参数时filter
方法 TypeScript 可以推断出类型I
从数组中提取谓词,但是当将谓词提取到单独的函数中时,这不再有效,TypeScript 会回退到基本对象类型{}
这打破了一切。
有没有办法来解决这个问题?说服 TypeScript 坚持使用泛型类型的一些技巧I
而不是将其解决为{}
当定义isNotNull
功能?或者这是 TypeScript 的限制,目前无法完成?