4

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;
    }

2 Answers 2

3

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

Comments

2

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

 var testString = test as string;

Comments

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.