【问题标题】:TypeScript, convert type 'string | undefined' to type 'string'TypeScript,转换类型 \'string | undefined\' 输入 \'string\'
【发布时间】:2022-08-08 00:27:47
【问题描述】:

我有这段代码,我想在其中转换类型为的测试变量字符串 |不明确的到 testString 类型细绳.我需要帮助来定义更改类型的逻辑。

@Function()
    public formatGit(tests: Gitdb): string | undefined {
        var test = tests.gitIssue; 
        var testString = ??
        return test;
    }

    标签: typescript


    【解决方案1】:

    您需要定义未定义字符串时应发生的行为。

    如果你想要一个空字符串而不是 undefined 你可以这样做:

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

    【讨论】:

      【解决方案2】:

      如果您确定 test 是一个字符串,您可以进行类型转换:

       var testString = test as string;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-22
        • 2017-01-29
        • 2021-11-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-20
        相关资源
        最近更新 更多