【问题标题】:Typescript - generic type guard for isEmpty functionTypescript - isEmpty 函数的通用类型保护
【发布时间】:2019-02-10 18:59:42
【问题描述】:

我无法正确实现泛型 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

【问题讨论】:

  • 我很难遵循这个。您能否将所有相关代码作为代码包含在此处(不是代码图片或代码链接),删除重现问题所需的任何内容,并清楚地指出您的问题所在(您期望什么与您得到什么)?提供minimal reproducible example 对获得有意义的答案大有帮助。

标签: typescript typescript-generics


【解决方案1】:

处理此问题的一种方法是将空值检查(undefined、null)与空值检查(''、[]{})分开。我倾向于为此使用两种类型的防护——isDefined 和 isEmpty。

第一个可能看起来像这样。注意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 添加了约束。

【讨论】:

  • 是的,我接近了类似的,我在对象测试中唯一缺少的是将对象显式类型转换为该对象或空对象的联合。以后我会用这个。非常感谢!
  • 我也会限制泛型,所以如果消费者想要支持不支持的 isEmpty 检查类型,他会得到编译时错误(它希望对象值出错,但我猜还是没有更好的东西:)) export const isEmpty = ( value: T | Empty ): value is Bottom
【解决方案2】:

这里

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

你有两个条件,其中只有一个是 countries 的类型保护,这就是为什么 countries 的类型在 if 中不会改变。

对于对象,{} 不代表空对象。除了null 和undefined 之外的任何东西都可以分配给{} 类型的变量。您可能想改用{ [prop: string]: never } 或{ [prop: string]: undefined }。

【讨论】:

  • 这些都不起作用。我已经试过了 :) { [prop: keyof T]: never } 或 { [prop: keyof T]: undefined }
【解决方案3】:

所以经过几次 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-11
    • 2018-10-02
    • 2020-11-11
    相关资源
    最近更新 更多