How to add a string type annotation to a variable or a constant in TypeScript?

September 2, 2021 - 3 min read

To add a string type annotation to a variable or a constant, you can declare the variable or constant followed by a : (colon) symbol and then the type string in TypeScript.

For example, let's say we have a variable called myName and want to only have the string type as the values. To do that we can annotate the type string to the myName variable like this,

// add string type to a variable
let myName: string;

After initialization, let's assign a string value of John Doe to the variable myName. It can be done like this,

// add string type to a variable
let myName: string;

// assign a string value to the myName variable
myName = "John Doe"; // ✅ allowed

As you can see from the above code TypeScript allowed us to assign the string value of John Doe to the variable myName since the allowed type for the myName variable is a string.

Now let's try to assign another value of number type 1 to the myName variable to see what happens,

// add string type to a variable
let myName: string;

// assign a string value to the myName variable
myName = "John Doe"; // ✅ allowed

// assign a value of type other than string
myName = 1; // ❌ not allowed. Type 'number' is not assignable to type 'string'.

As you can see that the TypeScript will throw an error saying that the Type 'number' is not assignable to type 'string'. which is also what we want to happen.

Bonus

Most of the time TypeScript will try to infer the type of the variable from the value it is assigned.

For example, let's declare a variable called personName and assign the string value of Lily Roy without actually declaring the type string as we did above. It can be done like this,

// Typescript infers the type from
// the value it is assigned
let personName = "Lily Roy";

Now if you hover over the variable personName we can see that TypeScript has automatically got that type of the variable personName is of type string.

Since the TypeScript has already got the type is of string value and whenever we try to reassign a value other than the type string, The compiler will throw errors like from the above.

See the execution of the above codes live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.