Home > Software engineering >  TypeScript, convert type 'string | undefined' to type 'string'
TypeScript, convert type 'string | undefined' to type 'string'

Time:03-04

I have this piece of code where I want to convert test variable which is of type string | undefined to testString of type string. I need help to define the logic to change the type.

@Function()
    public formatGit(tests: Gitdb): string | undefined {
        var test = tests.gitIssue; 
        var testString = ??
        return test;
    }

CodePudding user response:

You need to define the behaviour that should occur when the string is undefined.

If you want an empty string instead of undefined you could do something like this:

@Function()
public formatGit(tests: Gitdb): string {
    return tests.gitIssue ?? "";
}

If you want to throw an error you could do this:

@Function()
public formatGit(tests: Gitdb): string {
    if(tests.gitIssue === undefined){
        throw Error("fitIssue cannot be undefined");
    }

    return tests.gitIssue;
}

Or you can force the type like this, however, this will result in types that don't reflect the actual values at runtime:

@Function()
public formatGit(tests: Gitdb): string {
    return tests.gitIssue as string;
}

CodePudding user response:

You could do a type casting if you are sure test is a string:

 var testString = test as string;
  • Related