1

In the Typescript documentation here, it talks about

Difference between the static and instance sides of classes

In OOP language like C#, a static class is a class that can't be instantiated. How that is different from the static in Typescript?

wonderful world
  • 10,969
  • 20
  • 97
  • 194
  • Possible duplicate of [TypeScript static classes](https://stackoverflow.com/questions/13212521/typescript-static-classes) – Mihir Aug 13 '19 at 12:18

1 Answers1

2

Static class in C# is more than just being abstract. Static class means is can not be instantiated, inherited from and also sealed and can not be modified.

Static class in TypeScript is not natively supported but you can fake it:

function Protect(target: any): void {
  Object.freeze(target);
  Object.preventExtensions(target);
}

@Protect
abstract class StaticClass {
  constructor(){
    if (new.target) {
      throw new Error("Don't extend me");
    }
  }

  public static field = "foo";

  public static foo(): number {
    return 2;
  }
}

TypeScript only supports static fields, which simply means you can access those fields without creating an instance of the class.

If you use the declaration method above, you're forced to have all your public fields and methods as static, as you won't have any other way of accessing them.

Most JS/TS developers would tell you that if you want a static class, then don't do what I have done above and just use a plain object:

const MyStaticClass = {
  field: "foo",
  foo: () => 2
}

Object.freeze(MyStaticClass);
Object.preventExtensions(MyStaticClass);

That article is discussing something slightly different, relating to the how interfaces work in TS.

interfaces only understand the public face of things nothing private or the constructor.

They validate the class in terms of what it would have when instantiated so if you need to validate the constructor function then like that article you need to create a factory function (1 way of doing it) so you pass the class type into it and validate it's constructor through a proxied interface (as it can only read instance side public things).

Again, most JS/TS developers would tell you, if your arguments need validating, then create an interface out of an object that would contain them.

interface IStuff {
  a: number;
  b: string;
  c: boolean;
}

class MyClass implements IStuff {
  public a = this.params.a;
  public b = this.params.b;
  public c = this.params.c;

  constructor(private params: IStuff){}

  public getA(): number {
    return this.a;
  }

  public getB(): string {
    return this.b;
  }

  public getC(): boolean {
    return this.c;
  }
}
makeitmorehuman
  • 11,287
  • 3
  • 52
  • 76