Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign string | undefined to string in TypeScript?

Tags:

I want to assign a variable, which is string | undefined, to a string variable, as you see here:

private selectedSerialForReplace(): string | undefined {
    return this.selectedSerials.pop();
  }

luminaireReplaceLuminaire(params: {  "serial": string; "newserial": string; }, options?: any): FetchArgs {
............
}

luminaireReplaceLuminaire({serial: this.selectedSerialForReplace(), newserial: response.output});

I get this error:

Argument of type '{ serial: string | undefined; newserial: any; }' is not assignable to parameter of type '{ "serial": string; "newserial": string; }'

I cannot change selectedSerialForReplace() function to return anything else. Could you please help me?

like image 963
Sohrab Avatar asked Jul 19 '17 15:07

Sohrab


People also ask

How do you assign a string undefined to a string in TypeScript?

The typescript compiler performs strict null checks, which means you can't pass a string | undefined variable into a method that expects a string . To fix this you have to perform an explicit check for undefined before calling luminaireReplaceLuminaire() .

How do I combine strings in TypeScript?

The concat() is an inbuilt function in TypeScript which is used to add two or more strings and returns a new single string. Syntax: string. concat(string2, string3[, ..., stringN]);


1 Answers

The typescript compiler performs strict null checks, which means you can't pass a string | undefined variable into a method that expects a string.

To fix this you have to perform an explicit check for undefined before calling luminaireReplaceLuminaire().

In your example:

private selectedSerialForReplace(): string | undefined {
    return this.selectedSerials.pop();
}

luminaireReplaceLuminaire(params: {  "serial": string; "newserial": string; }, options?: any): FetchArgs {
    ............
}

const serial = this.selectedSerialForReplace();
if(serial !== undefined) {
    luminaireReplaceLuminaire({serial, newserial: response.output});
}
like image 78
Acevail Avatar answered Sep 20 '22 13:09

Acevail