【问题标题】:Typescript strictNullChecks and arraysTypescript strictNullChecks 和数组
【发布时间】:2017-08-30 19:37:11
【问题描述】:

我不完全理解 Typescript 在启用编译器选项 strictNullChecks 时的行为。似乎有时 Typescript(2.4.1 版)理解 string[] 中的项目是 string,但有时却没有:

interface MyMap {
    [key: string]: string[];
}

function f(myMap: MyMap) {
    const keys = Object.keys(myMap); // keys: string[] => Fine.
    for (let key of keys) { // key: string | undefined => Why?
        key = key as string // So a cast is needed.
        const strings = myMap[key]; // strings: string[] => Fine.
        const s = strings[0]; // s: string => Fine.

        // Error:
        // Argument of type 'string | undefined' is not assignable to parameter of type 'string'.
        // Type 'undefined' is not assignable to type 'string'.
        useVarArgs(...strings);
    }
}
function useVarArgs(...strings: string[]) {
}

2017 年 7 月 14 日更新:

只有在使用 downlevelIteration 时才会观察到这种奇怪的行为。我的tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "outDir": "target",
    "downlevelIteration": true,
    "strictNullChecks": true
  }
}

【问题讨论】:

  • 你使用的是什么版本的 TypeScript?您的代码在TypeScript Playground 上看起来不错。
  • 对不起,我忘了提。 2.4.1 版。还编辑了问题。
  • 我在 2.4.1 上测试了你的代码,它工作正常。 key 是需要强制转换的字符串,没有你提到的问题。
  • 看起来这是一个错误。我在 Typescript 的 Github 页面提交了一个问题:github.com/Microsoft/TypeScript/issues/17195
  • 我无法使用 2.4.1、strictNullChecksdownLevelIteration 重现此错误。您是否在单独的玩具项目中进行了复制?

标签: typescript definitelytyped


【解决方案1】:

经过进一步调查,我可以确认这不是 Typescript 问题。问题的根源是用于IteratorResult<T> 的类型。我用过@types/core-js 0.9.36:

interface IteratorResult<T> {
    done: boolean;
    value?: T;
}

value 是可选的,这在技术上是正确的,因为根据the iterator protocolvalue“当done 为真时可以省略。”正如我的问题所证明的那样,尽管在实践中,可选性并没有用处。

Typescript 附带的类型(“es2015”在tsconfig.json 的“lib”部分中配置,即文件lib.es2015.iterable.d.ts)采取更务实的方法,显然假设value 不会在@987654331 时使用@是true

interface IteratorResult<T> {
    done: boolean;
    value: T;
}

为了解决问题,您可以编辑@types/core-js 或将其替换为 Typescript 附带的库。但是,替换不是 100% 等效的 - 请查看 this issue 进行讨论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-04
    • 1970-01-01
    • 2017-02-15
    • 2018-11-04
    相关资源
    最近更新 更多