TypeScript Interfaces


Interfaces are definitions for an object that tells TypeScript what that object is going to be. Interfaces allow the compiler to check our code for errors as it is being compiled into JavaScript. This is a very good thing! We want to have those errors pointed out to us early rather than later. When they become apparent later, the errors will be harder to find and fix.

Let’s look at some code. Create a file with your favorite text editor (i.e. Atom or Visual Studio Code) in a directory where you store your code samples. I called my file interf.ts. The directory I am using in this example is C:\sites\typescript\codesamples.

Copy the code below into the file you created and then compile it and run it. To compile and run it you need to open a command prompt, change the directory to the location of the TypeScript file you need to compile and then run tsc as shown in the screen shot below.

// an interface is a definition or an object
interface Stark {
  name: string; //
}
// so this is simple enough; pass a string to the
// function which in turn displays it
function printNameString (aName : string){
  console.log(aName);
}
printNameString("a name string");
// Now we are passing an object stark of type Stark
function printName (stark : Stark) {
  console.log(stark.name);
}
// call the function printName and pass it an
// object that has a name property set to "Eddard"
printName({name:"Eddard"});
printName({name:"Johnson"});
// The code below will not compile by tsc:
// printName({address:"123 Main Street"});
// because there is no address property in the interface.

Here is a screen shot of the output in a Git Bash console.

Required Parameters

Let’s add an age parameter to the interface. For simplicity, the other function printNameString and its call have been deleted.

// an interface is a definition or an object
interface Stark {
  name: string;
  age: number;
}
function printName (stark : Stark) {
  console.log(stark.name);
}
// call the function printName and pass it an
// object that has a name property set to "Eddard"
printName({name:"Eddard"});

The above code will NOT compile. Why not? Here, age is a required parameter. We can make age optional by placing a question mark after the name of the parameter like so.

interface Stark {
  name: string;
  age?: number;
}

The above code will now compile by tsc. Let’s go back and make age required and use age in our code.

// an interface is a definition or an object
interface Stark {
  name: string;
  age: number;
}
function printName (stark : Stark) {
  console.log(stark.name);
  console.log("Age is: " + stark.age);
}
// call the function printName and pass it an
// object that has a name property set to "Eddard"
printName({name:"Eddard", age: 29});
Series Navigation<< TypeScript TypesTypeScript Interfaces Part 2 >>

Leave a comment

Your email address will not be published. Required fields are marked *