【问题标题】:typescript array.map lost returned typetypescript array.map 丢失返回类型
【发布时间】:2019-05-21 16:34:38
【问题描述】:

我预计以下代码中会出现类型错误,但对于 typescript 来说完全没问题,你能告诉我为什么吗?

export interface Structure {
    aaa: string;
}

export function f1(): Structure[] {  // OK for typescript, not for me
    const result = [].map(certState => {
        return {
            aaa: 'aaa',
            ADDITIONAL_FIELD: 'asdf'
        }
    });

    return result;
}

export function f2(): Structure[] { // ERROR for typescript (and for me)
        return [
            {
                aaa: 'sdf',
                ADDITIONAL_FIELD: 'asdf'
            }
        ]
    }

Here is the link

谢谢!

【问题讨论】:

    标签: arrays typescript dictionary types


    【解决方案1】:

    我刚刚了解到 Typescript 有一个仅针对对象字面量的精确类型的概念,因此 f1 不使用对象字面量,因此无法添加其他属性并且它对 typescript 有效。 f2 使用对象文字,因此不允许附加属性。这让我很害怕,但这就是 typescript 的工作原理

    【讨论】:

      【解决方案2】:

      错误是由于在f2() 中您直接返回结果。

      如果您将f2() 更改为

      export function f2(): Structure[] {
          const returnVal = [
              {
                  aaa: 'sdf',
                  ADDITIONAL_FIELD: 'asdf'
              }
          ]
      
          return returnVal;
      }
      

      那么就不会有编译错误了。

      TypeScript 使用structural typing 来确定类型兼容性,因此在您的f1() 代码中,result 属于类型

      {
         aaa: string,
         ADDITIONAL_FIELD: string
      }[]
      

      Structure[]兼容(类型缩小没有危险)。

      我不是 100% 确定为什么直接返回不起作用,但我的假设是,在 f2() 中,您告诉编译器“这个特定数组的类型为 Structure[]” 它说不,不是。当你在f1() 中有一个中间变量时,你说的是“这个函数返回Structure[]”,当你返回中间变量时,编译器会检查并说“好的result 匹配Structure[]”所以这个函数正在做它说。

      我很想知道其他人是否有更严格的解释

      【讨论】:

        猜你喜欢
        • 2019-10-02
        • 2020-04-03
        • 2021-10-17
        • 2017-05-16
        • 2019-06-24
        • 2021-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多