49

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?

2
  • Please try to improve your minimal reproducible example with reproducible code. What is the logic behind luminaireReplaceLuminaire? Is it supposed to accept undefined "serial" parameters? Commented Jul 19, 2017 at 15:36
  • You can specify type for useState(), e.g: const [username, setUsername] = useState<string | null>(null); Commented Apr 6, 2024 at 23:07

2 Answers 2

46

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});
}
Sign up to request clarification or add additional context in comments.

1 Comment

Side note, it's important to use != when checking undefined to catch null as well. null == undefined is true, null === undefined is false
40

If you are sure that serial could not be undefined you can use the ! post-fix operator

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

1 Comment

any quick solution if it's array of [string | undefined ] to [ string ]

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.