Typescript - isEmpty函数的泛型类型守护

问题描述 投票:2回答:3

我无法正确地实现通用isEmpty(value)在缩小类型约束下提供的值为空的对应物。

使用案例:

function getCountryNameById(countries: LookupItem[] = [], countryId?: number): string | undefined {

  if (isEmpty(countries) || !isNumber(countryId)) {

    // within this branch I would like to get countries argument to be narrowed to empty array type. 
    // Same would apply for other function which can have argument type of object or string. Why ? -> to prevent someone to do some mad code hacks like accessing non existent value from empty array ( which would happen on runtime ofc ) on compile time
    // $ExpectType []
    console.log(countries)

    return
  }

  // continue with code logic ...
  // implementation ...
}

关于约束对象的类似情况:

function doSomethingWithObject( data: { foo: string; bar: number } | object ){ 
   if(isEmpty(data)){
     // $ExpectType {}
     data

     // following should throw compile error, as data is empty object
     data.foo.toUpercase()

     return
   }

   // here we are sure that data is not empty on both runtime and compile time
}

isEmpty类型后卫实现:

export const isEmpty = <T extends AllowedEmptyCheckTypes>(
  value: T | AllowedEmptyCheckTypes
): value is Empty<T> => {
  if (isBlank(value)) {
    return true
  }

  if (isString(value) || isArray(value)) {
    return value.length === 0
  }

  if (isObject(value)) {
    return Object.keys(value).length === 0
  }

  throw new Error(
    `checked value must be type of string | array | object. You provided ${typeof value}`
  )
}

定义类型:

type EmptyArray = Array<never>
type Blank = null | undefined | void

/**
 * // object collects {} and Array<any> so adding both {} and Array<any> is not needed
 * @private
 */
export type AllowedEmptyCheckTypes = Blank | string | object

/**
 * Empty mapped type that will cast any AllowedEmptyCheckTypes to empty equivalent
 * @private
 */
export type Empty<T extends AllowedEmptyCheckTypes> = T extends string
  ? ''
  : T extends any[]
    ? EmptyArray
    : T extends object ? {} : T extends Blank ? T : never

它有点奇怪,因为它从类型角度正确缩小,但不在if / else分支内:

isEmpty for string values

isEmpty for array values

isEmpty for object values

代码可以在这里看到:https://github.com/Hotell/rex-tils/pull/13/files#diff-a3cdcb321a05315fcfc3309031eab1d8R177

相关问题:Type Guard for empty object

typescript typescript-generics
3个回答
2
投票

处理此问题的一种方法是将空检查(undefinednull)与空值检查(''[] {})分开。我倾向于使用两种类型的防护 - isDefinedisEmpty

第一个可能看起来像这样。请注意typeof检查 - 这使得它也适用于未声明的变量。

function isDefined<T>(value: T | undefined | null): value is T {
  return (typeof value !== 'undefined') && (value !== null);
}

对于空值,可以使用以下模型。

namespace Empty {
  export type String = '';
  export type Object = Record<string, never>;
  export type Array = never[];
}

type Empty =
  | Empty.Array
  | Empty.Object
  | Empty.String;

function isEmpty<T extends string | any[] | object>(subject: T | Empty): subject is Bottom<T> {
  switch (typeof subject) {
    case 'object':
      return (Object.keys(subject).length === 0);
    case 'string':
      return (subject === '');
    default:
      return false;
  }
}

type Bottom<T> =
  T extends string
    ? Empty.String
    : T extends any[]
        ? Empty.Array
        : T extends object
            ? Empty.Object
            : never;

底部值是正确推断的。

declare const foo: 'hello' | Empty.String;
declare const bar: [number, number] | Empty.Array;
declare const baz: Window | Empty.Object;

if (isEmpty(foo) && isEmpty(bar) && isEmpty(baz)) {
  console.log(foo, bar, baz);
}

编辑:按照建议在T上添加约束。


0
投票

所以在经过几次Twitter讨论和长时间的SO / Github搜索之后,我最终得到了以下解决方案:

  • 首先在isEmpty中检查null / undefined没有多大意义(虽然lodash.isEmpty处理这个问题,恕我直言,它做得太多而且没有非常明确的方式)
  • 因为{} |之间基本没有区别object | any[]类型后卫缩小将永远不会按预期工作
  • 最终解决方案只接受有效值来检查作为参数 - > js对象和字符串和保护返回never所以匹配值将是never的类型,因为无论如何,在if(isEmpty(value)){ ... }语句中执行任何进一步的登录没有任何意义,而不是终止程序或抛出错误

这是最后的实施:

const isEmpty = <T extends string | object | any[]>(
  value: T
): value is never => {
  if (isString(value) || isArray(value)) {
    return value.length === 0
  }
   if (isObject(value)) {
    return Object.keys(value).length === 0
  }
   throw new Error(
    `checked value must be type of string | array | object. You provided ${
      // tslint:disable-next-line:strict-type-predicates
      value === null ? 'null' : typeof value
    }`
  )
}

https://github.com/Hotell/rex-tils/pull/13/files#diff-68ff3b6b6a1354b7277dfc4b23d99901R50


0
投票

这里

if (isEmpty(countries) || !isNumber(countryId)) {

你有两个条件,其中只有一个是countries的类型后卫,这就是为什么countries的类型在if中没有变化的原因。

至于对象,{}不代表空对象。任何东西,除了nullundefined,都可以分配给{}类型的变量。您可能想要使用{ [prop: string]: never }{ [prop: string]: undefined }

© www.soinside.com 2019 - 2024. All rights reserved.