Close

TypeScript - Interface Hybrid Types

[Updated: Sep 13, 2018, Created: Sep 13, 2018]

TypeScript allows interfaces to represent hybrid types, i.e. interfaces can have combination of properties, function declarations, indexer and methods. This flexibility is allowed to get aligned with JavaScript dynamic nature. Let's see an example.

Example

interface Circle {
    radius: number;//property
    (x: number, y: number): void; //function declaration
    display(b: boolean);//method
    [state: string]: any; //indexer
}

//first create function
let c = function (x: number, y: number) {
    console.log(`center position: (${x}, ${y})`);
}

let circle: Circle = c as Circle; //type assertion on right side
circle.radius = 10;
circle.display = function (d: boolean) {
    console.log('circle displayed: ' + d);
}
circle['interactive'] = true;
circle['maximumRadius'] = 20;

console.log(circle);
circle(2, 5);// calling position function
circle.display(true);

Output

{ [Function: c]
radius: 10,
display: [Function],
interactive: true,
maximumRadius: 20 }
center position: (2, 5)
circle displayed: true

The compiled JavaScript:

//first create function
let c = function (x, y) {
    console.log(`center position: (${x}, ${y})`);
};
let circle = c; //type assertion on right side
circle.radius = 10;
circle.display = function (d) {
    console.log('circle displayed: ' + d);
};
circle['interactive'] = true;
circle['maximumRadius'] = 20;
console.log(circle);
circle(2, 5); // calling position function
circle.display(true);

Example Project

Dependencies and Technologies Used:

  • TypeScript 3.0.3
Interface Hybrid Types Select All Download
  • typescript-describing-hybrid-types
    • hybrid-type-example.ts

    See Also