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.

Jetbrains image

Build Secure, Ship Fast

Discover best practices to secure CI/CD without slowing down your pipeline.

Read more

👋 Kindness is contagious

Dive into this informative piece, backed by our vibrant DEV Community

Whether you’re a novice or a pro, your perspective enriches our collective insight.

A simple “thank you” can lift someone’s spirits—share your gratitude in the comments!

On DEV, the power of shared knowledge paves a smoother path and tightens our community ties. Found value here? A quick thanks to the author makes a big impact.

Okay