Search code examples
typescripttypesinterface

How to fix "TS2533: Object is possibly 'null' or 'undefined'" on dynamic object


I have a code like below:

interface Schema$CommonEventObject {
        formInputs?: {
            [key: string]: Schema$Inputs;
        } | null;
     }
interface Schema$Inputs {
        stringInputs?: Schema$StringInputs;
    }
interface Schema$StringInputs {
        value?: string[] | null;
    }
const commonEvent: Schema$CommonEventObject = event?.common ?? {};
const formValues = commonEvent.formInputs ?? {};
const topic = formValues?.['topic']?.stringInputs?.value[0];
const isAnonymous = formValues?.['is_anonymous']?.stringInputs.value[0] === '1';

it return error:

TS2532: Object is possibly 'undefined'.

TS2533: Object is possibly 'null' or 'undefined'

BTW, i'm using Schema$CommonEventObject from googleapis chat library:

how to fix these TS errors? Actually it working fine if I set strictNullChecks=false. But I want to set it as true to follow best practice.

I tried using null coalescing operator like below

  const topic = formValues?.['topic']?.stringInputs?.value[0] ?? '';

and still return the same error.

I also tried to use non-null assertion operator like below:

  const topic = formValues!.['topic']!.stringInputs!.value[0];

and return another error:

TS7053: Element implicitly has an 'any' type because expression of type '"topic"' can't be used to index type 'Schema$Inputs'.   Property 'topic' does not exist on type 'Schema$Inputs'.


Solution

  • I need to add Optional Chaining to stringInputs?.value. So, the correct code is

    const topic = formValues?.['topic']?.stringInputs?.value?.[0];
    

    but above still can return undefined, so I can add nullish coalescing operator like below

    const topic = formValues?.['topic']?.stringInputs?.value?.[0] ?? '';