コンパイラオプションstrictNullChecks
が有効なTypescriptの動作を完全に理解できません。Typescript strictNullChecksと配列
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日:
この奇妙な行動があることは時々活字体(バージョン2.4.1)はstring[]
内の項目がstring
あり、時にはそれがないことを理解しているようですdownlevelIteration
を使用した場合にのみ観測されます。マイtsconfig.json
:
{
"compilerOptions": {
"target": "es5",
"outDir": "target",
"downlevelIteration": true,
"strictNullChecks": true
}
}
どのタイプのTypeScriptを使用していますか?コードは[TypeScript Playground](http://www.typescriptlang.org/play)で上手く見えます。 – Saravana
申し訳ありませんが、私は言及を忘れてしまった。バージョン2.4.1。また編集された質問。 –
私は2.4.1であなたのコードをテストし、正しく動作しています。 'key'はキャストする必要のある文字列であり、あなたが言及した問題はありません。 – unional