Last active
June 20, 2024 02:18
-
-
Save Rudxain/6bbac0d68358b5487bc0c8fa6b3f0af7 to your computer and use it in GitHub Desktop.
Type Guards vs. Conditional Types
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
type numeric = number | bigint | |
const num_guard = (x: unknown): x is numeric => | |
typeof x == 'number' || typeof x == 'bigint' | |
const num_cond = <T,>(x: T) => ( | |
typeof x == 'number' || typeof x == 'bigint' | |
) as T extends numeric ? true : false | |
// this example is incomplete, | |
// I just kept it here because of the type-assertions | |
const f = <T,>(x: T): T extends numeric ? T : undefined => { | |
if (num_guard(x)) | |
return x as T extends numeric ? T : never | |
return undefined as T extends numeric ? never : undefined | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment