【问题标题】:Strange behaviour of callback function in TypescriptTypescript中回调函数的奇怪行为
【发布时间】:2021-12-06 14:41:19
【问题描述】:

我正在尝试解决 Typescript 中 filter 数组函数的问题,代码如下:

type Tag = string

type Args = {
  tags?: Tag[]
}

const func = async (args: Args) => {
  if (args.tags) {
    const entities = [
      { tagId: '1' },
      { tagId: '2' }
    ];
    
    const filtered = entities.filter(entity => args.tags.includes(entity.tagId));
    const mapped = args.tags.map(tag => tag + '_test');  
  }
};

当我尝试过滤 entities 数组时,此代码会引发 TS2532 错误:Object is possible undefined。由于某些原因,TS 解释器认为args.tags 可以是未定义的,因此无法调用include 函数。但是如您所见,上面有一个检查,map 函数也可以正常工作。

这里有什么问题?欢迎任何想法。

谢谢。

【问题讨论】:

    标签: javascript typescript


    【解决方案1】:

    TypeScript 不知道 filter 的回调会立即运行,所以如果 filter 的回调运行稍后(假设在 setTimeout 上),您的代码 会在这样的调用下崩溃:

    const a: Args = { tags: [] };
    await func(a);
    a.tags = undefined;
    // Later, the callback runs and accesses 'includes' of the undefined we just set
    

    您可以使用!

    entity => args.tags!.includes ...
    

    或者将值存储在const

    const tags = args.tags;
    if (tags) {
      // ...
      const filtered = entities.filter(entity => tags.includes ...
    

    【讨论】:

    • 非常感谢。不,我很清楚。
    【解决方案2】:
    type Args = {
      tags?: Tag[] // this means --> tags: Tag[] | undefined
    }
    

    Array.filter() 中使用可选链接和无效合并

    const filtered = entities.filter(entity => args?.tags?.includes(entity.tagId));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-27
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多