DEV Community 👩‍💻👨‍💻

Evaldas
Evaldas

Posted on

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'".

Top comments (0)

🌚 Life is too short to browse without dark mode