Search code examples
javascripttypescriptdefinition

string or object in typescript resulting in error while accessing


I have replicated the issue in this playground

enter image description here

I tried with different safety checks before accessing the inner key, nothing helped.


Solution

  • Since string is simple type, you should check its type with typeof

    type LabelValuesType2 = {
      label: string | { foo: string };
    }[];
    
    const values2: LabelValuesType2 = [{ label: { foo: 'value' } }, { label: 'value' }];
    
    values2.map(val => {
      console.log(typeof val.label == 'string' ? val.label : val.label.foo)
    })