Luis Valencia - MVP Luis Valencia - MVP - 1 year ago 767
TypeScript Question

how to sum 2 numbers in typescript

I have this properties

export interface IOurFirstSpfWebPartWebPartProps {
description: string;
n1: number;
n2: number;


Then I have this method

public render(): void {
this.domElement.innerHTML = `
<div class="${styles.ourFirstSpfWebPart}">
<div class="${styles.container}">
<div class="ms-Grid-row ms-bgColor-themeDark ms-fontColor-white ${styles.row}">
<div class="ms-Grid-col ms-u-lg10 ms-u-xl8 ms-u-xlPush2 ms-u-lgPush1">
<span class="ms-font-xl ms-fontColor-white">Welcome to SharePoint!</span>
<p class="ms-font-l ms-fontColor-white">Customize SharePoint experiences using Web Parts.</p>
<p class="ms-font-l ms-fontColor-white">${} + ${}</p>
<a href="" class="ms-Button ${styles.button}">
<span class="ms-Button-label">Learn more</span>

However this is printing 1+2 instead of 3.

Answer Source

You answer is related to implicit coercion in javascript. Simply put, you're concatinating two strings in a template and not adding two numbers.

When you hit the {}`s in your templating syntax, your numbers will be stringified. In essence you are then adding

"1" + "2" = "12" instead of 1 + 2 = 3

You can try two things 1. put both expressions inside of the {} ${ +}

if that still makes "12" then

2.try this: ${parseInt( + parseint(}
that will coerce both values to a number first, if it can be done.

you can learn more acout type coercion here: where it will really explain all the 'gotchas' out there about the + operator and implicit types

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download