Skip to content

Instantly share code, notes, and snippets.

@airglow923
Last active January 6, 2021 12:59
Show Gist options
  • Save airglow923/c43671b2caab34754545eb34c462f8a5 to your computer and use it in GitHub Desktop.
Save airglow923/c43671b2caab34754545eb34c462f8a5 to your computer and use it in GitHub Desktop.
Somewhat useless typescript code for generic but maybe useful in the future
const typePattern = /\s(.*)\]/;
interface GenericTaggable {
[Symbol.toStringTag]: string;
}
interface DefaultConstructible<T> {
new (): T;
}
function createSignature(value: any) {
return '<' + typePattern.exec(Object.prototype.toString.call(value))![1].toLowerCase() + '>'
}
class Factory<T> {
constructor(private ctor: new () => T) {}
getInstance(): T {
return new this.ctor();
}
}
function factory<T>(t: DefaultConstructible<T>): T {
return new t();
}
@airglow923
Copy link
Author

airglow923 commented Jan 6, 2021

Usage:

console.log(createSignature(true));       // <boolean>
console.log(createSignature(1));          // <number>
console.log(createSignature('asdf'));     // <string>
console.log(createSignature([1, 2, 3]));  // <array>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment