Created
January 1, 2020 21:03
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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