String in Typescript - simple explanation with examples

arikaturika

Arika O

Posted on May 16, 2020

String in Typescript - simple explanation with examples

Just like number, the string type is pretty straight forward: it specifies that we want something to be a string and a string only. It's used in the same manner:

let firstName: string = "Allan";
let lastName: string = "Korb";
Enter fullscreen mode Exit fullscreen mode

If we try to misuse it, and store a boolean inside of a variable of type number, for example, the editor will complain:

Alt Text

A super simple situation in which we could use this is when trying to print some of the properties of an object (let's say we got it back from the server after making an API call). We're trying to print a name made out of two strings but we use by mistake a property that stores a number.

Alt Text

Image source: Brett Jordan/ @brett_jordan Unsplash

πŸ’– πŸ’ͺ πŸ™… 🚩
arikaturika
Arika O

Posted on May 16, 2020

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

Sign up to receive the latest update from our blog.

Related

Getting Started with Typescript
typescript Getting Started with Typescript

July 21, 2024

Classes in TypeScript: With Challenges
keyof typeof Object
typescript keyof typeof Object

June 10, 2023

Part 6: Advanced TypeScript Topics
typescript Part 6: Advanced TypeScript Topics

May 23, 2023