Skip to content

Instantly share code, notes, and snippets.

@Rudxain
Last active June 20, 2024 02:18
Show Gist options
  • Save Rudxain/6bbac0d68358b5487bc0c8fa6b3f0af7 to your computer and use it in GitHub Desktop.
Save Rudxain/6bbac0d68358b5487bc0c8fa6b3f0af7 to your computer and use it in GitHub Desktop.
Type Guards vs. Conditional Types
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