Last active
July 26, 2020 12:00
-
-
Save valentinmakov/c59f3ef2d0565919f3b43b3fca690d37 to your computer and use it in GitHub Desktop.
Type example
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
interface IObject { | |
id: string | |
} | |
// long and ugly typing | |
const receiveDifferentTypes = (argument: string | 5 | IObject | null): number | {key: string} | undefined | (() => string) => { | |
if (argument === null) { | |
return undefined | |
} | |
if (typeof argument === 'object' && typeof argument.id === 'string') { | |
return {key: argument.id} | |
} | |
if (argument === 5) { | |
return argument * Math.random() * 10 | |
} | |
return (): string => 'i don\'t like strings' | |
} | |
// Single variable instead of long ugly line | |
type Argument = (string | 5 | IObject | null) | |
// Single variable instead of long ugly line | |
type Return = (number | {key: string} | undefined | (() => string)) | |
// nice and tidy typing | |
const receiveDifferentTypes2 = (argument: Argument): Return => { | |
if (argument === null) { | |
return undefined | |
} | |
if (typeof argument === 'object' && typeof argument.id === 'string') { | |
return {key: argument.id} | |
} | |
if (argument === 5) { | |
return argument * Math.random() * 10 | |
} | |
return (): string => 'i don\'t like strings' | |
} | |
receiveDifferentTypes('string') // Good | |
receiveDifferentTypes(5) // Good | |
receiveDifferentTypes({id: 'string'}) // Good | |
receiveDifferentTypes(null) // Good | |
receiveDifferentTypes({key: 'string'}) // Error: Argument of type '{ key: string; }' is not assignable to parameter of type 'string | 5 | { id: string; } | null' | |
receiveDifferentTypes2('string') // Good | |
receiveDifferentTypes2(5) // Good | |
receiveDifferentTypes2({id: 'string'}) // Good | |
receiveDifferentTypes2(null) // Good | |
receiveDifferentTypes2({key: 'string'}) // Error: Argument of type '{ key: string; }' is not assignable to parameter of type 'Argument' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment