Created
October 14, 2021 18:51
-
-
Save pixleight/4f5ab78cce6b894eead26774a0983025 to your computer and use it in GitHub Desktop.
Methods for tying the return type of a function to its arguments
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
// The return type matches the type of argument provided | |
const doSomething = <T>(data: T) : T[] => { | |
// processing... | |
return result; // array of type T | |
} | |
const something = doSomething(1) // type number[] | |
// For more complex narrowing... | |
// Interface maps a key to a certain type | |
interface TweetMap { | |
text: TextTweet, | |
media: MediaTweet, | |
} | |
const getTweetsByType = <T extends keyof TweetMap>( | |
type: T | |
): TweetMap[T][] => { | |
// processing... | |
return result; // Return type is tied to argument provided | |
} | |
const textTweets = getTweetsByType('text') // textTweets is now of type TextTweet[] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment