DEV Community

Discussion on: Simple trick to instance a class without `new`.

Collapse
 
yawaramin profile image
Yawar Amin • Edited

I highly recommend writing a helper function which returns an instance of the class. This lets you exactly control the return type. For example, that's how I prefer to do private fields/methods/etc.:

// dog.ts

export interface Dog {
  speak(): string
}

// The helper is exported and ensures that only the interface (public) fields are shown
export function newInstance(name: string): Dog {
  return new Impl(name)
}

// The class is hidden
class Impl {
  constructor(name: string) {
    this.name = name
  }

  speak(): string {
    return 'Woof!'
  }

  name: string
}