Created
December 2, 2021 09:52
-
-
Save JaosnHsieh/b76973b3eacc34dd298081e8128e2589 to your computer and use it in GitHub Desktop.
typescript function overloading is better than discriminated union because it can define return type of the function
This file contains hidden or 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 A = { command: 'a'; s: string }; | |
type B = { command: 'b'; b: number }; | |
function t(option: A | B) { | |
switch (option.command) { | |
case 'a': { | |
return 's'; | |
} | |
case 'b': { | |
return 1; | |
} | |
default: { | |
throw new Error('should never reached'); | |
} | |
} | |
} | |
const result = t({ command: 'a', s: '123' }); | |
/** | |
* const result: "s" | 1 | |
*/ |
This file contains hidden or 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
/* | |
* I like using discrimated union in my code described here: https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html#discriminating-unions | |
* But it doesn't defined return type of the function. | |
*/ | |
type A = { command: 'a'; s: string }; | |
type ReturnA = { returnA: string; aa: number }; | |
type B = { command: 'b'; b: number }; | |
type ReturnB = { returnB: number; bb: { nestedGuy: string } }; | |
function t(option: A): ReturnA; | |
function t(option: B): ReturnB; | |
function t(option: any): any { | |
if (option.command === 'a') { | |
return { | |
aa: 123, | |
returnA: '123', | |
} as ReturnA; | |
} | |
if (option.command === 'b') { | |
return { | |
bb: { nestedGuy: '123' }, | |
returnB: 123, | |
} as ReturnB; | |
} | |
} | |
const result = t({ command: 'a', s: '123' }); | |
/** | |
* const result: ReturnA | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment