Last active
October 15, 2018 14:21
-
-
Save minajevs/8cc998c9ec08c1d8d81ba600fd53a726 to your computer and use it in GitHub Desktop.
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 OptionalSpread<T> = | |
T extends undefined | |
? [] | |
: [T] | |
function foo<T = undefined>(...args: OptionalSpread<T>){ | |
const arg = args[0] // Type of: T = undefined | |
if (arg === undefined) | |
doThis() | |
else | |
doThat(arg) | |
} | |
// number | |
foo<number>(42) // OK | |
foo<number>() // ERROR: 1 argument expected | |
foo<number>("bar") // ERROR: 'bar' is not assignable 'number'. | |
// undefined explicit | |
foo<undefined>() // OK Now is possible! Yay! | |
foo<undefined>(42) // ERROR: 0 arguments expected | |
foo<undefined>(undefined) // ERROR: 0 arguments expected Even more safety! | |
// undefined inferred | |
foo() // OK | |
foo(42) // OK single argument type is inferred, can't do anything about it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment