我有一段代码,其中我想要将string类型的测试变量转换为string类型的testString。我需要帮助来定义更改类型的逻辑。
@Function()
public formatGit(tests: Gitdb): string | undefined {
var test = tests.gitIssue;
var testString = ??
return test;
}
发布于 2022-03-04 07:51:49
您需要定义字符串未定义时应该发生的行为。
如果您想要一个空字符串而不是未定义的字符串,您可以这样做:
@Function()
public formatGit(tests: Gitdb): string {
return tests.gitIssue ?? "";
}
如果您想抛出一个错误,您可以这样做:
@Function()
public formatGit(tests: Gitdb): string {
if(tests.gitIssue === undefined){
throw Error("fitIssue cannot be undefined");
}
return tests.gitIssue;
}
但是,也可以强制使用这样的类型,这将导致在运行时不反映实际值的类型:
@Function()
public formatGit(tests: Gitdb): string {
return tests.gitIssue as string;
}
发布于 2022-03-04 07:52:21
如果确定test
是字符串,则可以进行类型转换:
var testString = test as string;
https://stackoverflow.com/questions/71348070
复制相似问题