1

Is there a way to set obj['a32']['a']=3232 without using if statement and without using ! to tell compiler to not check? I tried using ?. but it throws The left-hand side of an assignment expression may not be an optional property access.(2779) Playground: link

interface A{
    [key:string]:{[key:string]:number};
}

const obj:A = {};

const k='a32';
if(!obj[k]){
 obj[k]={};
}

obj[k]['a']=3232; // Object is possibly 'undefined'.(2532)

obj[k]?.['a']=3232; // The left-hand side of an assignment expression may not be an optional property access.(2779)

obj[k]!['a']=3232; // this works but never checks if obj['a32] is defined


if(obj[k]){
    obj[k]['a']=3232;
}

1 Answer 1

3

I'm not sure why you want to avoid using an if statement, but you could use the logical nullish assignment operator ??= instead:

TS Playground link

interface A {
  [key: string]: {[key: string]: number};
}

const obj: A = {};

const k = 'a32';

(obj[k] ??= {})['a'] = 3232;

console.log(obj); // { a32: { a: 3232 } }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.