【问题标题】:TypeScript empty row in string literal字符串文字中的 TypeScript 空行
【发布时间】:2022-11-22 19:43:18
【问题描述】:

我想创建一个带有可选值 numberOfResidents 的字符串文字。

function mapBuildingToComment(building: Building) {
    return `
    ### Building information ###
    Street: ${building.address.street}
    HouseNumber: ${building.address.houseNumber}
    ${mapNumberOfResidents(building.numberOfResidents)}
    City: ${building.address.city}
    `
}

function mapNumberOfResidents(numberOfResidents?: string) {
    if (!numberOfResidents) return ''

    return `Number of residents: ${numberOfResidents}`
}

我现在的问题是,当 numberOfResidents 未定义时,我的输出中有一个空行。

Output:
    ### Building information ###
    Street: Teststreet
    HouseNumber: 1

    City: Test

我怎样才能做到没有空行并且城市在门牌号正下方?

【问题讨论】:

    标签: typescript string string-literals


    【解决方案1】:

    删除换行符并仅在需要时添加它

    function mapBuildingToComment(building: typeof b) {
        return `
        ### Building information ###
        Street: ${building.address.street}
        HouseNumber: ${building.address.houseNumber}
    ${building.numberOfResidents ? '
        ' + mapNumberOfResidents(building.numberOfResidents) : ''}
        City: ${building.address.city}
        `
    }
    
    function mapNumberOfResidents(numberOfResidents?: string) {
        if (!numberOfResidents) return ''
    
        return `Number of residents: ${numberOfResidents}`
    }
    
    const b = {address: {street: '123', houseNumber: 245, city: 'asd'}, numberOfResidents: '3'}
    console.log(mapBuildingToComment(b))
    b.numberOfResidents = ''
    console.log(mapBuildingToComment(b))
    

    另一种选择是使用 s.replaceAll(/ s+(?= )/g, '') 从结果中删除空行

    【讨论】:

      猜你喜欢
      • 2017-11-25
      • 1970-01-01
      • 2017-08-30
      • 2017-03-31
      • 2014-12-15
      • 2016-05-15
      • 2013-12-20
      • 1970-01-01
      相关资源
      最近更新 更多