Typescript: Optional chaining and assigning to array items

Created on 16 Dec 2019  路  4Comments  路  Source: microsoft/TypeScript



TypeScript Version: 3.7.2


Search Terms: optional chaining array items

Code
Is there any reason why I cannot do this:

interface MyInterface {
    temp: number;
}

const a: Array<MyInterface | null> = [];

a[0]?.temp = 0;

and instead I'm forced to use something like this?:

interface MyInterface {
    temp: number;
}

const a: Array<MyInterface | null> = [];

if (a[0])
    a[0].temp = 0;

Expected behavior:
a[0] doesn't exists, so assigning number 0 will be skipped.

Actual behavior:
Error: The left-hand side of an assignment expression may not be an optional property access.(2779)

Playground Link: https://www.typescriptlang.org/play/?target=2&ssl=5&ssc=35&pln=5&pc=40#code/JYOwLgpgTgZghgYwgAgLIE8CS5ryQbwChkTlIBbABwC5kQBXcgI2gG5CBfQwhAexADOYZHFoBBKFDjoAPBmyRYiFAB869ADYaAfMgC8yANoBddoTiGADMYD8AOgqV9yS2eAxkACgvWAlMVIfYwcIKmdXIA

Related Issues:

Working as Intended

Most helpful comment

This is technically not the appropriate venue to discuss it (since it's just part of the ECMAScript feature, not TypeScript) - but just curious, what would you want to happen?

Do you want to create a property? Or do you want to not perform the assignment if it's not there?

All 4 comments

This is not supported by the specification. See https://github.com/tc39/proposal-optional-chaining#not-supported

This is technically not the appropriate venue to discuss it (since it's just part of the ECMAScript feature, not TypeScript) - but just curious, what would you want to happen?

Do you want to create a property? Or do you want to not perform the assignment if it's not there?

I expected that assignment will be skipped and no property will be created (no side effects).

This issue has been marked 'Working as Intended' and has seen no recent activity. It has been automatically closed for house-keeping purposes.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhuravlikjb picture zhuravlikjb  路  3Comments

Antony-Jones picture Antony-Jones  路  3Comments

manekinekko picture manekinekko  路  3Comments

uber5001 picture uber5001  路  3Comments

wmaurer picture wmaurer  路  3Comments