Austin Story

Ruby, Rails and Javascript Blog

Powered by Genesis

TypeScript Interfaces Basics

February 23, 2016 By Austin Story Leave a Comment

Interfaces describe the shapes of various javascript objects. It is a fancy way to say describe the composition of objects and also the outputs of functions.

[code]
function sayHello(personObj: {name: string}) {
alert("Hello " + personObj.name);
}
[/code]

This function will check that whatever we pass in AT LEAST has a property of name that is a string.

[code]
Minimum Working
var bob = {name: ‘Bob’};
sayHello(bob);

But extras are just ignored, so this will work too
var alice = {name: ‘Alice’, likes: ‘TypeScript, AngularJS, Ruby’, home: ‘Missouri’};
sayHello(alice);
[/code]

A more fancy way to write this would be with an interface declaration

[code]
interface hasName {
name: string;
}

function sayHello(personObj: hasName) {
alert("Hello " + personObj.name);
}
[/code]

You can also set variables as optional in interfaces by adding a ? at the end. This will help typescript catch typos and also explain the contract of what you can accept.

[code]
interface hasPersonality {
interests?: string;
}
[/code]

Filed Under: Javascript, TypeScript Tagged With: interfaces, Javascript, typescript

Categories

  • AngularJS
  • Books
  • Devise
  • Elasticsearch
  • ES6
  • Information Security
  • Integrations
  • Javascript
  • Linux
  • Minitest
  • PhoneGap
  • Programming
  • React
  • Redux
  • Ruby
  • Ruby on Rails
  • Stripe
  • Testing
  • Theory
  • TypeScript
  • Uncategorized
  • Vue
  • Webpack