An Introduction To TypeScript: Static Typing and Interfaces
Will Diep
Posted on January 22, 2020
TypeScript is a strongly-typed superset of JavaScript in which means it adds some syntactical benefits to the language while still letting you write normal JavaScript if you want to. It encourages a more declarative style of programming through utilizing features such as:
- Static typing
- Interfaces
- Modules
- Classes
Variables
let name = "Sam"
let age = 40
let enjoysCoding = true
let name: string = "Sam"
let age: number = 40
let enjoysCoding: boolean = true
There isn't much of a difference here. The difference is we are explicitly telling our program what type each variable is. Telling our program such specific information gives our system the opportunity to catch errors that we may have down the road.
If were to reassign our age variable to another type:
let age = 40
age = 'forty-five'
TypeScript would have a red underline on the reassigned variable expressing an error:
Interface
interface Person {
firstname: string;
lastname: string;
}
Interfaces are used to define the structure of objects. In our example above, we are expliciting that any variable of type Person will be an object comprising of a firstname and lastname property in which are both string types. You can think of this as we are creating custom types for our object.
Why is this useful? It explicits to the compiler in addition to your future self and other developers what type of data to expect. We are modelling the object properties allowing us to reference them in case we need to debug them. It's a common practice to put your interfaces at the top of TS files. This gives the developer an idea of the data types used for each property.
Functions
function greeter(person: Person):string {
return "Hello, " + person.firstname + " " + person.lastname;
}
Our greeter function passes in a person parameter in which we are expecting it to be from type Person from the Interface. This promotes us to use the interface Person's first name and last name and prevent headaches as passing in the wrong Interface would throw error right away. Further, the :string after the function parameters states the data type we expect this function to return when we invoke it.
Installation:
1) Typescript Playground:
https://www.typescriptlang.org/play/
2) Local setup
npm install -g typescript
# greeter.ts
function greeter(person: string) {
return "Hello, " + person;
}
var user = "Will User";
document.body.innerHTML = greeter(user);
On the command line, run the TypeScript compiler:
tsc greeter.ts
Output:
function greeter(person) {
return "Hello, " + person;
}
var user = "Will";
document.body.innerHTML = greeter(user);
Posted on January 22, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.