-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
use constructor.name-based instanceof helper
- Loading branch information
Showing
3 changed files
with
35 additions
and
13 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
/** | ||
* Pretty much like the `instanceof` operator, but should work across different realms. Necessary for zod because some installations | ||
* might result in this library using the commonjs zod export, while the user's code uses the esm export. | ||
* https://github.com/mmkal/trpc-cli/issues/7 | ||
* | ||
* Tradeoff: It's possible that this function will return false positives if the target class has the same name as an unrelated class in the current realm. | ||
* So, only use it for classes that are unlikely to have name conflicts like `ZodAbc` or `TRPCDef`. | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
export const looksLikeInstanceof = <T>(value: unknown, target: new (...args: any[]) => T): value is T => { | ||
let current = value?.constructor | ||
do { | ||
if (current?.name === target.name) return true | ||
current = Object.getPrototypeOf(current) as Function | ||
} while (current?.name) | ||
return false | ||
} |
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