Last active
May 6, 2023 07:04
-
-
Save enpitsuLin/15ccb1d1b167ffaa6b9455c929883d7e to your computer and use it in GitHub Desktop.
Code snippets
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
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)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
andnew (): String
that can handler universally