Can someone help explain this code from the recent 'Dont migrate to tRPC' stream
On the stream at around the 2hr 07min mark Theo writes the following code:
const sendTweetToDiscord = async (
tweet: NonNullable<
inferAsyncReturnType<typeof getRecentTrashTweets>["data"]
>[number]
) => {
... other code
};
I am new to typescript so i am trying to understand whats going on here.
From what i understand we are getting the return type of getRecentTrashTweets, then accessing the data property which is of type number, but because the number could also be undefined we use NonNullable to explicitly state that it will always be a number and not undefined.
Is this correct?
Thanks in advance
4 Replies
i havent watched the stream, but i can answer this in an abstract way
what you wrote is close, but not quite correct
when reading types, i find that the easiest way to parse them is to start from the inside and work your way out
typeof getRecentTrashTweets
is just the type of that entire function
inferAsyncReturnType<typeof getRecentTrashTweets>
gets the return type of this function (which is presumably an async function, the inferAsyncReturnType
helper turns the promise into just a regular type
inferAsyncReturnType<typeof getRecentTrashTweets>["data"]
accesses the data
field that is included in the object that this function returns
NonNullable<inferAsyncReturnType<typeof getRecentTrashTweets>["data"]>
implies that the return might be null, this helper says give me this type but without nullish values
finally, NonNullable<inferAsyncReturnType<typeof getRecentTrashTweets>["data"]>[number]
implies that the data
property was something like Array<Tweet> | null
(where tweet is presumably an object type of some sort)
by giving
[number]`, you're saying "this type is an array, give me the type of an item inside the array
Thanks for taking the time to explain this. I really appreciate it.
That makes a lot of sense.
I'm still a little confused as to how [number] relates to {text: string} Is "number" just any variable, could we write [textData] instead and it still work? Thanks
I'm still a little confused as to how [number] relates to {text: string} Is "number" just any variable, could we write [textData] instead and it still work? Thanks
Number just means any item in the array
If the array can contain multiple types, then it would give you a union type of everything that one item in the array could possibly be
Best to open up an editor or ts playground and try it for yourself
awesome mate thanks for the help again!