How to assign string | undefined to string in TypeScript?

前端 未结 2 1141
醉梦人生
醉梦人生 2021-01-11 10:08

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

private selectedSerialForReplace(): string | undefined {
            


        
相关标签:
2条回答
  • 2021-01-11 10:12

    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});
    }
    
    0 讨论(0)
  • 2021-01-11 10:25

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

    luminaireReplaceLuminaire({serial: this.selectedSerialForReplace()!, newserial: response.output});
    
    0 讨论(0)
提交回复
热议问题