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;
    }
                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;
}
                        You could do a type casting if you are sure test is a string:
 var testString = test as string;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With