Typescript for beginners: string

evaldasburlingis

Evaldas

Posted on September 12, 2020

Typescript for beginners: string

As programmers we are using strings to work with textual data all the time.

In typescript we have a word string to check if the type is string.

In the function below we are checking whether the argument supplied is a string and we are making sure that we return a string.

function getName(name: string) : string { 
return `Hi, my name is ${name}` 
} 

getName("Paul") // Hi, my name is Paul
getName() // error "Expected 1 arguments, but got 0."
getName(true) // error "Argument of type 'boolean' is not assignable to parameter of type string"

To break it down into smaller bits, this functions reads as follows:
function getName(argument : type to check) : type we want to return {.....}

We can also type check variables:

let postCode : string = "LT-3422"; 
postCode = 4232// error "Type 'number' is not assignable to type 'string'".
💖 💪 🙅 🚩
evaldasburlingis
Evaldas

Posted on September 12, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related