TypeScript Tutorial
TypeScript Strings
string holds text. Concatenate, measure length, and slice — with a type the compiler can check.
Declare a string
A string holds a sequence of characters. Write the type after the name, then a value in double quotes. You do not include a header. tsc already knows string.
Example
const word: string = "TypeScript";
console.log(word);Try this at /typescript/try with Try it in TypeScript. The TypeScript editor compiles with tsc.
Concatenate with +
+ joins strings. If one side is a string, the other side is converted to text and glued on. Two number operands still add. Mix a string with a number and you concatenate, so"n=" + 3 is n=3.
Example
const first: string = "Ada";
const last: string = "Lovelace";
const full: string = first + " " + last;
console.log(first);
console.log(full);
console.log(first + " wrote programs");length and the first character
length is a property, not a call. It is how many characters are in the string. Index[0] is the first character, type string of length 1. Indexes start at zero, so the last character is at length - 1 when the string is not empty.
Example
const word: string = "TypeScript";
console.log(word.length);
console.log(word[0]);
console.log(word[1]);Do not read word[0] when the string is empty. You get undefined at run time. Checklength first, or only index strings you just filled with text.
slice copies a piece
slice(start, end) returns a new string from index start up to, but not including,end. Omit end and it runs to the end. The original string does not change.
Example
const name: string = "StudyGrid";
const tag: string = name.slice(0, 5);
console.log(name);
console.log("first five: " + tag);
console.log(name.slice(5));Change 5 to 4 and compile again. The slice shortens. C++ usedsubstr for this idea; TypeScript uses slice.
Input is already a string
readLine() at /typescript/try returns a string, including spaces on that line. You do not need a separate “read a word” call. Type a full name in the stdin box, then compile.
| Need | Tool |
|---|---|
| Join text | + |
| Count characters | .length |
| Take a piece | .slice(start, end) |
| Read a line in the editor | readLine() |
Quotes
Double quotes and single quotes both make strings: "A" and 'A' are the same type. TypeScript has no separate char type. Next: math functions on the global Math object.