String Type in TypeScript is defined using string
keyword and declared using single quotes ( '
), double quotes ( "
) and backtick ( `
) for multi-line template literals. TypeScript also supports string interpolation.
Declaring String in TypeScript
We can declare string using string
keyword, this is termed as explicitly type declaration. Implicitly typescript will also determine based on the value stored in variable.
Read more about Type Inference
// Explicit string type declaration
// syntax
<variable type> <variable name> : string;
let tutorialName : string;
tutorialName = 'String Type in TypeScript'
//Implicit string type declaration
let websiteName = 'Elegant TypeScript';
// TypeScript will infer type based on the value stored in variable.
Defining String using single and double quotes
let name : string = 'Elegant TS Tutorial' ;
let topic : string = "Strings in TypeScript" ;
// short hand declaration.
let firstName : string = 'David' , lastName : string = " Brown " ;
Defining String using backtick ( ` ) and String Interpolation
Backtick is used to define template literals which wraps multi-line strings and supports string interpolation i.e. changing a placeholder value using a variable.
// Multi Line String
let content : string = ` Elegant TypeScript tutorial,
learn TypeScript from ground zero. `
String interpolation helps us to replace values in a defined string using variables to make it dynamic.
// String Interpolation
let name : string = 'John'
let welcomeMessage : string = ` Hi ${name} welcome to Elegant TypeScript Tutorial.`
console.log (welcomeMessage)
// output
Hi John welcome to Elegant TypeScript Tutorial.
Summary
- Strings in TypeScript can be declared using single quote (
'
), double quote ("
) , backtick (`
). - String interpolation can also be achieved using template literals and backtick (
`
).