Typescript Data Types -String

April 19, 2018 Oclemy Typescript Data Types 1 minute, 38 seconds

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.