Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pixleight/4f5ab78cce6b894eead26774a0983025 to your computer and use it in GitHub Desktop.
Save pixleight/4f5ab78cce6b894eead26774a0983025 to your computer and use it in GitHub Desktop.
Methods for tying the return type of a function to its arguments
// 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