Home > Mobile >  if - else for readonly in TypeScript
if - else for readonly in TypeScript

Time:08-26

I wanted to add an if check to a readonly type

 readonly clinicalDataForSamples = remoteData<ClinicalData[]>(
        {
            await: () => [this.studies, this.samples],
            invoke: () =>
                this.getClinicalData(
                    REQUEST_ARG_ENUM.CLINICAL_DATA_TYPE_SAMPLE,
                    this.studies.result!,
                    this.samples.result,
                    [
                        CLINICAL_ATTRIBUTE_ID_ENUM.CANCER_TYPE,
                        CLINICAL_ATTRIBUTE_ID_ENUM.CANCER_TYPE_DETAILED,
                    ]
                ),
        },
        []
    );

I want to check if this.samples.result is undefined using

    if (typeof this.studies.result === 'undefined')
        throw new Error('Failed to get studies');

How can I implement this?

CodePudding user response:

Make a function that will check it, and then call it when you use the studies:

function assertNotUndefined(value: any, msg?: string) {
    if (typeof value === "undefined") throw new Error(msg);

    return value; // passed check; return back
}
    readonly clinicalDataForSamples = remoteData<ClinicalData[]>(
        {
            await: () => [this.studies, this.samples],
            invoke: () =>
                this.getClinicalData(
                    REQUEST_ARG_ENUM.CLINICAL_DATA_TYPE_SAMPLE,
                    assertNotUndefined(this.studies.result, "Failed to get studies"),
                    this.samples.result,
                    [
                        CLINICAL_ATTRIBUTE_ID_ENUM.CANCER_TYPE,
                        CLINICAL_ATTRIBUTE_ID_ENUM.CANCER_TYPE_DETAILED,
                    ]
                ),
        },
        []
    );

CodePudding user response:

If you add brackets and a return statement to your lambda function, you can add as many statements as you want, i.e.:

 readonly clinicalDataForSamples = remoteData<ClinicalData[]>(
        {
            await: () => [this.studies, this.samples],
            invoke: () => {
                if (typeof this.studies.result === 'undefined')
                      throw new Error('Failed to get studies');

                return this.getClinicalData(
                    REQUEST_ARG_ENUM.CLINICAL_DATA_TYPE_SAMPLE,
                    this.studies.result!,
                    this.samples.result,
                    [
                        CLINICAL_ATTRIBUTE_ID_ENUM.CANCER_TYPE,
                        CLINICAL_ATTRIBUTE_ID_ENUM.CANCER_TYPE_DETAILED,
                    ]
                );
            },
        },
        []
    );
  • Related