DEV Community

Cover image for The lowly Interface
John Peters
John Peters

Posted on

1

The lowly Interface

We want to hook up window resize events easily. So we create this function.

import { Subject } from 'rxjs';
interface wh {
  width: string;
  height: string;
}
const sub = new Subject<wh>();
export function _resizeEvent(): Subject<wh> {
  debugger;
  window.addEventListener('resize', (ev) => {
    let window = ev.target as Window;
    let ele = window.document.activeElement as HTMLElement;
    let width = ele.offsetWidth.toString();
    let height = ele.offsetHeight.toString();
    sub.next({ width: width, height: height });
  });
  return sub;
}
Enter fullscreen mode Exit fullscreen mode

To use the code above:

import { _resizeEvent } from './functions/observers';

_resizeEvent().subscribe(result=>{
       this.width=result.width;
    }); 
Enter fullscreen mode Exit fullscreen mode

Intellisense now shows us both properties as we type.

Alt Text

Note that interface definitions, unlike class definitions do not support the new keyword. This is pretty much the only difference between the two.

Do your career a favor. Join DEV. (The website you're on right now)

It takes one minute and it's free.

Get started

Top comments (0)

11 Tips That Make You a Better Typescript Programmer

typescript

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!