indieboy
indieboy

Reputation: 53

TypeScript, convert type 'string | undefined' to type 'string'

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

Upvotes: 4

Views: 5733

Answers (2)

Youssouf Oumar
Youssouf Oumar

Reputation: 45835

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

 var testString = test as string;

Upvotes: 2

CampbellMG
CampbellMG

Reputation: 2220

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

Upvotes: 3

Related Questions