DEV Community

Evaldas
Evaldas

Posted on

2 1

Typescript for beginners: number

One time I've been working with Rest API and there was this one property, that was supposed to be a number. Instead, it wasn't, it was a string and it broke my function. At the time I wasn't using typescript and it took some time to find a problem. With typescript, it would have been so much quicker!

Typescript basic type number:

function addTax(num: number) : number {
    const tax : number = num * .21;

    return num + tax
}
addTax(100) // 121
addTax("100") // 10021 // error "Argument of type 'string' is not assignable to parameter of type 'number"

Top comments (1)

Collapse
 
eljayadobe profile image
Eljay-Adobe

One of the many beauties of TypeScript is that type annotation of parameters and returns allows for static type checking at transpile time, which eliminates a big category of errors that otherwise don't show up until run time. (Even if there is thorough unit testing.)

For small programs written by one person, that's not a huge win. But for medium or large programs, or even small programs written by two or more people... it's a huge grief saver.

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up