Skip to content

Instantly share code, notes, and snippets.

@enpitsuLin
Last active May 6, 2023 07:04
Show Gist options
  • Save enpitsuLin/15ccb1d1b167ffaa6b9455c929883d7e to your computer and use it in GitHub Desktop.
Save enpitsuLin/15ccb1d1b167ffaa6b9455c929883d7e to your computer and use it in GitHub Desktop.
Code snippets
const arr = [new Date(), new RegExp(''), new String('test'), 'test', /test/, new Number(1), 1, BigInt(1), 1n]
type InferConstructorType<C> = C extends DateConstructor ? Date : C extends ((...args: any[]) => infer T) | (new (...args: any[]) => infer T) ?
T : unknown
function filterInstance<Constructor extends ((...args: any[]) => any) | (new (...args: any[]) => any)>(
t: Constructor
) {
return (item: any, _index: number, _arr: any[]): item is InferConstructorType<Constructor> => {
if (typeof item === 'object') {
return item instanceof t
}
// for literal
return item.constructor === t
}
}
const regexps = arr.filter(filterInstance(RegExp))
const strings = arr.filter(filterInstance(String))
const numbers = arr.filter(filterInstance(Number))
const bigints = arr.filter(filterInstance(BigInt))
const dates = arr.filter(filterInstance(Date))
@enpitsuLin
Copy link
Author

confusion thing, why did DateConstructor has (): string? Is there any constructor built-in that has the same thing?

for new() was one type, but for () was another type, not like String (): string and new (): String that can handler universally

image

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