Typescript: Automatic adding undefined to dictionary maps

Created on 17 Feb 2017  路  2Comments  路  Source: microsoft/TypeScript

My suggestion was hidden in the closed #13792, so i open a new issue about that.

Every object map can be undefined on a random key access. Can we catch this in a general approach or do we have to find every needed definition?

I just changed my own code and had an issue with for in loops. Tested with TS2.1 perhaps this has changed in 2.2

const StringDict: { [index: string]: string; } = {foo: 'bar'};
for (let key in StringDict) {
   const thisStringValue = StringDict[key];
}
const StringDict2: { [index: string]: string | undefined; } = {foo: 'bar'};
for (let key in StringDict2) {
   const StringValueOrUndefined = StringDict2[key];
}

I cannot imagine a case where StringValueOrUndefined is really able to become undefined. So an extra check to make TS happy would burn CPU cycles.

Working as Intended

Most helpful comment

One of the questions was if this | undefined should be added by typescript itself for such constructions.

All 2 comments

I cannot imagine a case where StringValueOrUndefined is really able to become undefined.

const StringDict2: { [index: string]: string | undefined; } = {foo: 'bar', qua: undefined};
for (let key in StringDict2) {
   const StringValueOrUndefined = StringDict2[key];
}

So an extra check to make TS happy would burn CPU cycles.

This is why the postfix ! operator exists.

One of the questions was if this | undefined should be added by typescript itself for such constructions.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

remojansen picture remojansen  路  3Comments

weswigham picture weswigham  路  3Comments

blendsdk picture blendsdk  路  3Comments

bgrieder picture bgrieder  路  3Comments

siddjain picture siddjain  路  3Comments