我沒有完全理解Typescript的行爲,並且啓用了編譯器選項strictNullChecks
。看來,有時打字稿(版本2.4.1)瞭解到,在string[]
的項目是string
,有時則沒有: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日:
這種奇怪的行爲是僅在使用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