The only article you need to read to become an Expert in TypeScript!
TypeScript is an open-source high-level programming language from Microsoft that extends JavaScript by integrating static typing and optional type annotations.
It retains all the features of JavaScript while introducing a robust type system for dynamic type checking during development.
Developers can specify types for variables, function parameters, return values, and other elements, thereby improving tooling support and detecting errors at compile time rather than runtime.
If you have prior experience with JavaScript, TypeScript will prove useful. Typescript is utilized across various frontend frameworks such as NextJs, React, and Vue, all of which also offer support for JavaScript. Moreover, familiarity with object-oriented programming (OOP) principles will further enhance your utilization of TypeScript.
Let’s discuss about the key features of Typescript starting with the static-type checking:
- Static-type checking checks your code for errors on the go. Static type systems define the structures and actions of our values before execution. A type-checker such as TypeScript utilizes this data to inform us when there is an error.
- Another key feature of typescript is the tsc compiler that you can use to type check your code by running the tsc command in a terminal. Note, before you can use the tsc command, ensure that typescript is installed globally via npm.
- TypeScript supports Enums, which allow developers to define a set of named constants. Typescript support both string and numeric based Enums
- TypeScript also offers support for classes, interfaces, and custom types. Developers can define classes in an object-oriented programming (OOP) fashion, as well as create custom data structures and contracts. Interfaces serve as blueprints for objects, ensuring that objects adhere to a specified shape.
- Typescript also supports static methods in classes and also Generics that allows for code reusability.
Basic Types
Let’s delve into the fundamental types provided by TypeScript, which encompass various data types including strings, numbers, booleans, and the versatile “any” type, among others. Additionally, we’ll explore more advanced types and their applications within TypeScript.
The most commonly used types in typescript are string, boolean and number. Strings represent string values like “hello john” and number is for numbers either integers, floats, decimal are all classified as number type in typescript. And finally, boolean represents true or false.
Lets define these types right away in code , we are going to use the typescript playground to do this starting with the string type. Visit the Typescript playground https://www.typescriptlang.org/play and follow along.
String type
/*javascript*/
//let message
//message = "Welcome to typescript"
//console.log(message)
/*typescript version*/
let message:string
message = "Welcome to typescript" //use a number and you get an error
console.log(message)The code above shows how to define a string in javascript and typescript. The typescript version defines the type for the message variable and does static type checking.
Typescript type checker will highlight the error if a number is assigned to the string message variable, therefore allow us to see the errors on the go and avoid pitfalls
Number type
Decimals, floats and integers are all classified as number type in typescript.
let age:number
age = 30 //must be a number
//age = 30.5 //also works
//age = 20 + 10 //also works
console.log(age)the variable “age” must be a number because they type number is used.
In javascript age can take any type such and number + string. If we use the javascript approach this is what we get:
let age;
age = 10 + "hello"; //javascript will see this as a string
//age = 10 + "hello" + true; //javascript will also see this as a string
//age = 10 > 10 //now a boolean
console.log(age)when we run this code, we get “10 hello” as the result. Javascript is going to see the variable as a string because the age variable does not have a type, so it is going to accept any value.
Boolean type
The boolean type is a conditional type that can be either true or false in typescript.
let age:number = 30;
let mustBe18:boolean = age > 18
console.log(mustBe18)Array type
Arrays in typescript are similar to arrays in javascript. But with typescript you can add type annotations that ensures type safety. Let’s start by defining an array in javascript
/*arrays in javascript*/
let numbers;
numbers = [1,2,3] //can accept any value
numbers = [1,2,3,"hello",true]
console.log(numbers)
console.log(numbers[3])JavaScript, being an untyped language, is prone to type safety bugs, occurring when an unintended type is mistakenly used instead of the expected one. This is the problem typescript solves.
In typescript, you can define an array of string, booleans, number or even the any type array. Typescript also support generic array classes.
let numbers = number[]
numbers = [1,2,3,4]
//numbers = [1,2,3,4,""] //this will cause an error
console.log(numbers)let word:string[] = ["welcome","to"]
word.push("typescript")
//word.push(1) //would cause an error
console.log(word)let word:any[] = ["welcome","to"]
word.push("typescript",1,[3,4,5])
console.log(word[4][1]) //returns 4The any type as the name implies support all types
We can also use the generic Array<> class in typescript to define arrays.
let numbers: Array<number>
numbers = [1,2,3,4]
//numbers = [1,2,3,4,""] //this will cause an error
console.log(numbers)
let word:Array<string> = ["welcome","to"]
word.push("typescript")
//word.push(1) //would cause an error
console.log(word)
let words:Array<any> = ["welcome","to"]
words.push("typescript",1,[3,4,5])
console.log(words[4][1]) //returns 4In TypeScript, there is a special type known as “any.” It serves as a versatile placeholder, allowing you to bypass type checking when a specific value’s type is uncertain or irrelevant to your current needs. We have used this type in the example above.
In TypeScript, you have the ability to specify both parameter types and return types for functions. This means you can declare the types of input parameters as well as the type of the value returned by the function.
function Sum(nums:Array<number>):number
{
//The reduce() method reduces all elements in an array into a single value.
let result:number = nums.reduce((accumulator,currentValue)=>
{
return accumulator + currentValue
})
return result
}
console.log(Sum([1,2,3,4]))the Sum function defines a type for the nums parameter and also the type of the function return type which is a number
Object type
So far, we’ve been utilizing primitive types in the examples provided. Another frequently encountered type, particularly when dealing with JSON data, is the object type, representing any JavaScript value with properties.
function DisplayProfile({name,age}:{name:string,age:number}):any
{
return {name, age}
}
let profile = DisplayProfile({name:"John", age:30});
console.log(`${profile.name} is ${profile.age} years old`);The code above accept an object type as a parameter and each of those properties are assigned to their types.
Optional Properties
In Typescript, you can designate optional properties by appending a question mark to the property name. This informs TypeScript that the property is not required. Simply add the question mark after the property name to achieve this.
function DisplayProfile({name,age}:{name:string,age?:number}):any
{
return {name, age}
}
let profile = DisplayProfile({name:"John"});
console.log(`${profile.name} is ${profile.age} years old`);The age property is optional by appending the question mark after the property name. When we run this piece of code in the playground, we get “John is undefined years old”. To remove the undefined, we can specify the default value for age or use the double question “??” to define a value of the variable is undefined
function DisplayProfile({name,age}:{name:string,age?:number}):any
{
return {name, age}
}
let profile = DisplayProfile({name:"John"});
console.log(`${profile.name} is ${profile.age??18} years old`);We can also do it this way:
function DisplayProfile({name,age=18}:{name:string,age?:number}):any
{
return {name, age}
}
let profile = DisplayProfile({name:"John"}); //no age
console.log(`${profile.name} is ${profile.age} years old`);The age defaults to 18 when the age variable is not specified in the console.log message
Union types
Another noteworthy feature in TypeScript is the Union types.Union types in TypeScript allow variables or parameters to have multiple possible types. They are denoted using the pipe operator between each type. Below is how to declare a Union type in the typescript playground.
function DisplayProfile({name,age}:{name:string,age:number|string}):any
{
return {name, age}
}
let profile = DisplayProfile({name:"John", age:"Thirty"}); //age can be a number or string
console.log(`${profile.name} is ${profile.age} years old`);Type aliases
Type aliases in TypeScript allow us to create custom names for types, making our code more expressive and reusable. Instead of repeatedly defining complex types or combinations of existing types, we can create a single alias that represents them. This not only enhances code readability but also simplifies maintenance and reduces duplication. With type aliases, we can encapsulate intricate type definitions into easily understandable names, promoting code clarity and maintainability.
type profile =
{
name:string,
age:number|string
}
function DisplayProfile({name,age}:profile):any
{
return {name, age}
}
const AgeVerification = (profile:profile) =>
{
return profile.age as number > 18
};
let profile = DisplayProfile({name:"John", age:30});
console.log(`${profile.name} is ${profile.age} years old`);
console.log(`${profile.name} ${AgeVerification(profile) && 'is liable' || 'is not liable'}`);the profile type alias can be reused in different places thus avoiding the need to create duplicates.
Interfaces
Another TypeScript feature resembling type aliases is interfaces. Interfaces provide a means to outline the structure of objects, serving as contracts that mandate the properties and methods an object should possess. They support extension, allowing for enhanced flexibility. While type aliases and interfaces share similarities, interfaces offer the added capability of extension, distinguishing them from type aliases while type aliases cannot be reopened to add new properties.
interface IProfile
{
name:string,
age:number|string
}
function DisplayProfile({name,age}:IProfile):any
{
return {name, age}
}
const AgeVerification = (profile:IProfile) =>
{
return profile.age as number > 18
};
let profile = DisplayProfile({name:"John", age:30});
console.log(`${profile.name} is ${profile.age} years old`);
console.log(`${profile.name} ${AgeVerification(profile) && 'is liable' || 'is not liable'}`);interface IProfile
{
name:string,
age:number|string
}
class Profile implements IProfile //implements the contract interface
{
name: string;
age: string|number;
constructor(name:string,age:number)
{
this.name=name;
this.age = age;
}
}
const profile = new Profile("John",30);
console.log(`${profile.name} is ${profile.age} years old`);Another feature in TypeScript is type assertion, which is similar to casting in object-oriented programming languages like C#, achieved through the “as” keyword. There are instances where TypeScript may not accurately infer the type of a value, but as a developer, you possess that knowledge. By utilizing the “as” keyword, you can explicitly specify the actual type just as shown in the previous examples.
const AgeVerification = (profile:IProfile) =>
{
return profile.age as number > 18 //because age is a number and a string we need to do type assertion
};TypeScript Classes
If you are familiar with object oriented programming this section on classes should come in handy. Typescript supports the class keyword introduced in ES2015.
Get Charles’s stories in your inbox
Join Medium for free to get updates from this writer.
Classes in TypeScript provide a way to implement object-oriented programming (OOP) concepts such as encapsulation, inheritance, and polymorphism.
Let’s explore what you can do with classes in typescript starting with class definition with fields. Fields can be known as a public writable property on a class and they can have an optional type annotation with its default to any type if no type is assigned.
The example below shows a class declaration with two assigned fields, one annotated with the number type and the other not annotated which would automatically use the “any” type.
class Profile
{
name: string;
age; //defaults to any type
constructor(name:string,age)
{
this.name=name;
this.age = age;
}
}
const profile = new Profile("John","30");
console.log(`${profile.name} is ${profile.age} years old`);Readonly fields
Fields can also have readonly modifiers just as with OOP programming languages such as C#, a readonly field can be assigned only through its constructor. The example below shows a class declaration with readonly fields that can only be assigned through its constructor. If you try to assign it outside its constructor, you get a typescript error.
class Profile
{
readonly name: string;
age:number;
constructor(name:string,age:number)
{
this.name = name;
this.age = age;
}
tryToAssign = (name) => name; //wrong!!! can only assign name in the constructor
}
const profile = new Profile("John",30);
console.log(`${profile.name} is ${profile.age} years old`);Constructors
A notable feature of classes in TypeScript is constructors. Constructors are similar to constructors in object-oriented programming (OOP) languages, supporting overloading, parameters, and default parameter values. It’s worth noting that constructors lack return types, can have type parameters, and require the `super()` method to be called if the class extends another, granting access to the `this` keyword. To explore this further, experiment with the example provided on the TypeScript playground.
class ProfessionalProfile
{
linkedIn:string
github:string
constructor(linkedIn:string, github:string){
this.linkedIn=linkedIn
this.github=github
}
}
class Profile extends ProfessionalProfile
{
name: string;
age:number;
constructor(name:string,age:number)
{
super("linkedin.com","github.com"); //super calls the base constructor
this.name=name;
this.age = age;
}
}
const profile = new Profile("John",30);
console.log(`${profile.name} is ${profile.age} years old`);
console.log(`professional profile: linkedin: ${profile.linkedIn} github: ${profile.github}`)class Profile
{
name?: string;
age?:number
constructor()
constructor(name?:string,age?:number)
{
this.name=name;
this.age=age;
}
}Methods
Methods are like functions in javascript that can contain parameters and can also have a return type. Up to this point, we’ve been illustrating methods in our examples, so this should come in handy.
class Profile
{
Method1()
{
console.log("in method one")
}
Method2 = () =>
{
console.log("in method two")
}
Method3 = (name:string) =>
{
console.log(name)
}
}
new Profile().Method1()Getters and Setters
Classes in typescript can also have getters and setters accessors. Accessors resemble properties in OOP, so this should come in handy. Let’s define an accessor in the playground right away using the code below.
class Profile {
_fullname:string = ""; //can also have access visibility
get fullname() {
return this._fullname;
}
set fullname(value) {
this._fullname = value;
}
}
const profile = new Profile()
profile.fullname ="John"
console.log(profile.fullname)Interfaces
In TypeScript, you can adhere to an interface by implementing its signature in a concrete class. This class must fulfil the structure defined by the interface and can also introduce its own fields and methods. This is achieved through the “implements” clause. We have already seen this in action in previous examples, let define this further.
interface IProfile {}
interface IRank {}
//an interface can also extend another interface
interface IScore extends IRank {}
class ProfessionalProfile {}
//implement the interface IProfile
class Profile implements IProfile {}
//can also extend a class and implement an interface
class Profile2 extends ProfessionalProfile implements IProfile {}
//can also implement multiple interfaces
class Profile3 implements IProfile, IRank {}Access modifiers
In object-oriented programming languages like C#, access modifiers regulate access to methods and declare properties or methods as either publicly accessible or restricted within a class. Similarly, in TypeScript, you can define member visibility to specify whether properties or methods are accessible beyond the scope of its class.
These member visibilities are — The public which is the default, the private and the protected member visibilities.
When you define a method without no visibility, then it defaults to the public member visibility.
A public member can be accessible anywhere. So far, in our examples we have not specified any member visibility. By default we have been working with public visibility because it is the default when you don’t specify.
However, when you want a class to have methods, properties or fields that can only be private to that class, use the private visibility. When a method is declared as private, even subclasses cannot access it.
However, if you want only a child or subclass to access its base class methods or fields but you don’t other classes to have access to it, you can use the protected member visibility.
class ProfessionalProfile {}
class Profile
{
private name:string;
constructor(name:string)
{
this.name=name
}
private Display = () => console.log(this.name);
}
const profile = new Profile("John")
profile.name //cannot access profile.name because its has private member visibility
profile.Display() //cannot access profile.name because its has private member visibility
class ProfessionalProfile {
protected linkedin?:string //only subclass can have access to this field
get LinkedIn()
{
return this.linkedin
}
set LinkedIn(value) {
this.linkedin = value;
}
}
class Profile extends ProfessionalProfile
{
private name:string;
constructor(name:string)
{
super();
this.name=name
}
private Display = () => console.log(this.name);
DisplayProfessionalProfile = () => console.log(this.linkedin); //default to public member visibility
}
const profile = new Profile("John")
profile.LinkedIn = "https://linkedin.com";
profile.DisplayProfessionalProfile();Static members
In TypeScript, classes can have static members, but the concept of static classes doesn’t exist. Unlike some object-oriented programming languages like C#, where a class can be designated as static, TypeScript doesn’t support static classes. Instead, you define static members within a class using the `static` keyword. These members belong to the class itself, allowing you to access them directly via the class name without needing to instantiate the class.
Static members can also have access modifiers which we discussed earlier such as public, private and protected and can also be inherited.
class ProfessionalProfile {
protected static linkedin?:string //only subclass can have access to this field
static get LinkedIn()
{
return this.linkedin
}
static set LinkedIn(value) {
this.linkedin = value;
}
}
class Profile extends ProfessionalProfile
{
private name:string;
constructor(name:string)
{
super();
this.name=name
}
private Display = () => console.log(this.name);
static DisplayProfessionalProfile = () => console.log(this.linkedin); //default to public member visibility
}
Profile.LinkedIn = "https://linkedin.com";
Profile.DisplayProfessionalProfile();Generic classes
Another amazing feature you can do with typescript are creating generic classes that ensures type safety and reusability. Generics does not only work with classes but also interfaces. To understand how generics works, let dive into the code:
class Data<T>
{
data:T;
constructor(data:T)
{
this.data=data;
}
DisplayData()
{
console.log("type of data is: " + typeof this.data);
}
}
var data = new Data(1);
data.DisplayData()The Data class can accept any type
interface IProfile<T>
{
data:T;
}
class Data implements IProfile<number>
{
data;
constructor(data:number)
{
this.data=data;
}
DisplayData()
{
console.log("type of data is: " + typeof this.data);
}
}
var data = new Data(1);
data.DisplayData()Abstract classes
Typescript also allows you to define abstract classes just as you can do with other programming languages such as C#. An Abstract class is a class that cannot be instantiated and it serves as a base class for subclasses. Methods and fields can also be declared as abstract. Let see an example
abstract class Base
{
abstract SayHello():void;
}
class Derived extends Base
{
SayHello() //this overrides the Base class SayHello() method
{
console.log("hello")
}
}
new Derived().SayHello();TypeScript Enums
Enums in TypeScript offer a method for defining a collection of named constants, a feature absent in JavaScript.
There are various types of enums: Numeric Enums and String Enums, which are more popular. Additionally, there are Heterogeneous Enums, though their usage is infrequent.
Numeric enums in TypeScript are automatically assigned a default value of “0”. However, if you specify a starting value, subsequent values will be incremented accordingly. For instance, if you assign “1” as the initial value, the next value will be “2”.
enum Account
{
SAVINGS = 1,
CURRENT,
FIXED
}
console.log(Account.SAVINGS)String enums in TypeScript differ from numeric enums. With string enums, you must assign each member a string literal value.
enum Account
{
SAVINGS = "Savings",
CURRENT = "Current",
FIXED="Fixed"
}
console.log(Account.SAVINGS)TypeScript in HTML
To use typescript in html just as we normally do in javascript by including the <script> tag and specifying the path to script in the src attribute, in typescript we need to compile it using this command:
npm install -g typescriptNote: Node js needs to be installed before running npm
After installing typescript globally, the we can run this command:
tsc file1.tsThe tsc command is used to compile typescript to javascript and also used to check for errors. After compilation, it generate a file1.js javascript file that can be used in html files.
Conclusion
Up to this point, we’ve explored the fundamental aspects of TypeScript which is a superset of javascript. TypeScript is gaining popularity due to its ability to perform all functionalities achievable with JavaScript, along with additional capabilities like Enums, which are not possible in JavaScript alone. Web frameworks such as Angular, React and Vue supports TypeScript due to its robust type checking features.
Enhance your TypeScript skills by enrolling in our course, “Typescript, React and NextJs for Beginners.” This comprehensive course provides you with the essential tools to elevate your proficiency as a web developer. React stands as one of the most prevalent frontend libraries, powering renowned web applications like Instagram, WhatsApp, Netflix, and many others. Moreover, Next.js serves as a robust framework for React. Don’t let this opportunity pass you by — enroll now!




