使用复杂的“ isEmpty”检查时进行类型推断

时间:2018-12-06 12:22:14

标签: typescript type-inference

我具有以下功能,其功能类似于ramdas isEmpty,但根据我的需要量身定制:

/**
 * Checks if a value is empty.
 * It will return true for the following cases:
 * null, undefined, empty string, empty Set, empty Map, an object without properties.
 * @param input Can be any value.
 * @example
 *
 *     isEmpty([1, 2, 3]); //=> false
 *     isEmpty([]); //=> true
 *
 *     isEmpty(''); //=> true
 *
 *     isEmpty(null); //=> true
 *     isEmpty(undefined); //=> true
 *
 *     isEmpty({}); //=> true
 *
 *     isEmpty(new Set([1, 2, 3])); //=> false
 *     isEmpty(new Set()); //=> true
 *
 *     isEmpty(0); //=> false
 *
 *     isEmpty(new Date()); //=> true
 *     isEmpty(Date.now()); //=> false
 */
export const isEmpty = (input: any): boolean => {
  const isMapOrSet = input instanceof Map || input instanceof Set;
  return input === null
    || input === undefined
    || (input instanceof String ? input.length > 0 : false)
    || (isMapOrSet ? input.size === 0 : false)
    || (!isMapOrSet && input instanceof Object ? Object.keys(input).length === 0 : false);
};

使用此函数非常简单,但是我对boolean返回类型不满意,因为TypeScript无法推断该函数提供的空检查。

例如,以下代码非常好,但是TypeScript会在someResult[0]调用中抱怨可能为null。

const someResult: [] | null = getStuffFromAPI();
const x = isEmpty(someResult)
? {}
: someResult[0]; // TypeScript will complain about a possible _null_ here.

所以问题是: 如何改善函数的签名,以便TypeScript可以正确推断返回类型?

我试图通过使用conditional types为自定义返回类型建模,但是我无法弄清楚如何正确地实现它。

要使其100%清楚我在搜索什么,这里有一些伪代码(请注意,HasNoElementsIsEmpty在TS中不存在):

type IsEmpty<T> =
  T extends null | undefined ? true :
  T extends Map & HasNoElements ? true :
  T extends Set & HasNoElements ? true :
  T extends String & IsEmpty ? true :
  T extends Object & IsEmpty ? true :
  false;

也许我想得太多了,但我想拓宽我的视野。

1 个答案:

答案 0 :(得分:0)

已通过改进TypeScript 3.4中泛型的类型推断解决了此问题。因此,在上面的示例中,我基本上获得了我想要“免费”使用的所有正确类型签名。