Home > other >  TypeScript empty row in string literal
TypeScript empty row in string literal

Time:11-22

I want to create a string literal with the optional value 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}`
}

My problem now is, when numberOfResidents is undefined, there is an empty line in my output.

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

    City: Test

How can I achieve that there is no empty line and City is directly below the house number?

CodePudding user response:

remove the newline and add it only if you need it like

function mapBuildingToComment(building: typeof b) {
    return `
    ### Building information ###
    Street: ${building.address.street}
    HouseNumber: ${building.address.houseNumber}\
${building.numberOfResidents ? '\n    '   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))

another option is to remove empty lines from result with s.replaceAll(/\n\s (?=\n)/g, '')

  • Related