string type
- TypeScript course
- Beginner
- Lesson 6/89
- 4 min
Learn to define text with the string type.
What is the string type?
The string type holds text data: a single letter, word, sentence or long paragraph. To mark a variable as string, you write a colon and the type name after the variable name; this is called a type annotation.
let isim: string = "Ayşe";
let sehir: string = "İstanbul";
console.log(isim); // AyşeThe value inside quotes is text, the : string outside tells the compiler the type.
String concatenation
You can join two strings with the plus (+) sign. The result is again a string. This is the simplest way to combine several pieces into one text.
let on: string = "Kara";
let son: string = "deniz";
let tam: string = on + son;
console.log(tam); // KaradenizPractice Your first string variable
Declare a string variable named mesaj and assign "Merhaba dünya". Then print its value with console.log.
Starter code
// mesaj adında string değişken tanımla ve "Merhaba dünya" ata
// değeri yazdırSample solution
let mesaj: string = "Merhaba dünya";
console.log(mesaj);Expected output
Merhaba dünya
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 In the line let mesaj: string = "merhaba";, which part is the type annotation?
- let
- mesaj
- : string Correct answer
- "merhaba"
Explanation: The colon and the type name after it (string) together form the type annotation.
2 Complete the type annotation
let renk: ____ = "mavi";
let renk: string = "mavi";
Explanation: In TypeScript the text type is written lowercase string; the capital String is something different.
3 Parts of a string declaration
| Term | Meaning |
|---|---|
let isim |
variable declaration |
: string |
type annotation |
"Ayşe" |
text value |
console.log |
output function |