Typescript Data Types -String

Strings are sequences of characters.

In Typescript you can specify string literals. Literals are the exact value a string will contain.

Declaring and Initializing String

You can split it into declaration and assignment:

var my_vehicle: string;
my_vehicle = "Spacecraft"; 

You can also join declaration and assignment:

var my_vehicle = "Spacecraft"; 
//or explicit
var my_vehicle: string = "Spacecraft"; 

String Concatenation

String Concatenation means joining two strings together.

We can use the +(addition operator) to concatenate strings:

var firstname: string = "Mike";
var lastname: string = "Jones";
var fullname = firstname + lastname;

Strings as Instance Fields and Passing Strings as Arguments

Just like any other data type strings can be declared as instance fields and they can be passed around as argument to methods and constructors.

Let's look at a full example:

class Person {
    name: string;
    age: number;
    element: HTMLElement;
    span: HTMLElement;

    constructor(name: string, age: number,element: HTMLElement) {
        this.name = name;
        this.age = age;
        this.element = element;
    showName() {
        this.element.innerHTML +=" My name is " + this.name;
    showAge() {
        this.element.innerHTML +=" My age is " + this.age;
    greet(greeting: string) {
        this.element.innerHTML +=" And I say " + greeting;


window.onload = () => {
    var el = document.getElementById('content');
    var p = new Person("Mike Jones",67,el);
    p.greet("Hello World");

Then the html code:

<!DOCTYPE html>

<html lang="en">
    <meta charset="utf-8" />
    <title>Typescript Strings</title>
    <link rel="stylesheet" href="css/materialize.min.css" type="text/css" />
    <script src="app.js"></script>
    <nav class="light-blue lighten-1" role="navigation">
        <div class="nav-wrapper container">
            <a id="logo-container" href="" class="brand-logo">Camposha.info</a>

    <div class="container" id="content">
        <h3>Mr String</h3>

And we get this: Typescript Strings

Best regards.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:


What do You Think

Previous Post