Skip to content

Instantly share code, notes, and snippets.

@armanozak
Created January 1, 2020 21:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armanozak/0da27fe5464d15146a7ef863d69ea207 to your computer and use it in GitHub Desktop.
Save armanozak/0da27fe5464d15146a7ef863d69ea207 to your computer and use it in GitHub Desktop.
[Callable Constructors in TypeScript] How to Merge Ambient Class Declaration with Function Declaration #typescript #tips
// requires TypeScript v3.6+
export { DeepBoolean };
type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};
declare class DeepBoolean<T = any> {
constructor(source: T);
readonly source: T;
toString(): string;
valueOf(): boolean;
}
function DeepBoolean(this: undefined | void, obj: any): boolean;
function DeepBoolean(this: DeepBoolean, obj: any): DeepBoolean;
function DeepBoolean(
this: DeepBoolean | undefined | void,
obj: any,
): DeepBoolean | boolean {
if (!(this instanceof DeepBoolean)) return checkDeepTruth(obj);
(this as Mutable<DeepBoolean>).source = obj;
this.valueOf = () => checkDeepTruth(obj);
this.toString = () => String(checkDeepTruth(obj));
return this;
}
function checkDeepTruth(obj: any): boolean {
return !!obj && (
typeof obj === "object"
? Object.keys(obj).every(key => checkDeepTruth(obj[key]))
: true
);
}
// EXAMPLE
const source = [{ a: { b: true, n: 1, s: 'TypeScript' } }];
const dB = new DeepBoolean(source);
console.log(dB.valueOf()); // true
console.log(DeepBoolean(source)); // true
source[0].a.s = '';
console.log(dB.valueOf()); // false
console.log(DeepBoolean(source)); // false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment