Strings are sequences of characters.
In Typescript you can specify string literals. Literals are the exact value a string will contain.
You can split it into declaration and assignment:
//declaration
var my_vehicle: string;
//assignment
my_vehicle = "Spacecraft";
You can also join declaration and assignment:
//implicit
var my_vehicle = "Spacecraft";
//or explicit
var my_vehicle: string = "Spacecraft";
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;
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.showName();
p.showAge();
p.greet("Hello World");
};
Then the html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Typescript Strings</title>
<link rel="stylesheet" href="css/materialize.min.css" type="text/css" />
<script src="app.js"></script>
</head>
<body>
<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>
</nav>
<div class="container" id="content">
<h3>Mr String</h3>
</div>
</body>
</html>
And we get this:
Best regards.