DEV Community

Cover image for String in Typescript - simple explanation with examples
Arika O
Arika O

Posted on • Updated on

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

Top comments (0)