【发布时间】: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、
strictNullChecks和downLevelIteration重现此错误。您是否在单独的玩具项目中进行了复制?
标签: typescript definitelytyped