[英]Typescript strictNullChecks and arrays
我没有完全理解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-07-14:
只有在使用downlevelIteration
时才会观察到这种奇怪的行为。 我的tsconfig.json
:
{
"compilerOptions": {
"target": "es5",
"outDir": "target",
"downlevelIteration": true,
"strictNullChecks": true
}
}
经过进一步调查,我可以确认这不是打字稿问题。 问题的起源是用于IteratorResult<T>
的类型。 我使用过@types/core-js 0.9.36
:
interface IteratorResult<T> {
done: boolean;
value?: T;
}
value
是可选的,这在技术上是正确的,因为根据迭代器协议 , value
“完成时可以省略”。 正如我的问题所证明的那样,选择性在实践中并没有用。
使用Typescript附带的类型(在tsconfig.json
的“lib”部分中配置的“es2015”,即文件lib.es2015.iterable.d.ts
)采用更实用的方法,显然假设在done
时不会使用该value
是true
:
interface IteratorResult<T> {
done: boolean;
value: T;
}
为了解决这个问题,您可以编辑@types/core-js
或将其替换为Typescript附带的库。 但是,替换不是100%等效 - 请查看此问题进行讨论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.