Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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;
    }
like image 873
indieboy Avatar asked Sep 14 '25 12:09

indieboy


2 Answers

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;
}
like image 173
CampbellMG Avatar answered Sep 17 '25 05:09

CampbellMG


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

 var testString = test as string;
like image 33
yousoumar Avatar answered Sep 17 '25 05:09

yousoumar