Skip to content

Instantly share code, notes, and snippets.

@jooeycheng
Created February 3, 2023 02:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jooeycheng/94f43e9bcd98d5b20285846fe87363eb to your computer and use it in GitHub Desktop.
Save jooeycheng/94f43e9bcd98d5b20285846fe87363eb to your computer and use it in GitHub Desktop.
TypeScript Notes
class Material {
public static readonly ACRYLIC = new Material(`ACRYLIC`, `AC`, `Acrylic`);
public static readonly ALUM = new Material(`ALUM`, `AL`, `Aluminum`);
public static readonly CORK = new Material(`CORK`, `CO`, `Cork`);
public static readonly FOAM = new Material(`FOAM`, `FO`, `Foam`);
// private to diallow creating other instances of this type.
private constructor(public readonly key: string, public readonly id: string, public readonly name: string) {}
public toString(): string {
return this.key;
}
}
declare namespace Material {
type Keys = Exclude<keyof typeof Material, "prototype">;
}
const materialKeys: Material.Keys[] = [`ACRYLIC`, `FOAM`];
for (const key of materialKeys) {
const material: Material = Material[key];
// ...
}
class Outer {
static Inner = class {};
}
declare namespace Outer {
type Inner = typeof Outer.Inner.prototype;
}
console.log(Outer.name); // Outer
console.log(Outer.Inner.name); // Inner
let _inner: Outer.Inner;
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Default name is just "Inner".
* Can get difficult to identify if we log class names, and multiple "Inner" classes exist.
*
* Override the static `.name` to return namespaced-name "AnotherOuter.Inner",
* which mirrors how we reference it in code.
*/
class AnotherOuter {
static Inner = class {};
}
Object.defineProperty(AnotherOuter.Inner, "name", {
value: `${AnotherOuter.name}.${AnotherOuter.Inner.name}`,
writable: false,
});
console.log(AnotherOuter.Inner.name); // AnotherOuter.Inner
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment