I have the following code:
export const getTagsByType = (type: string, rawData: any) => {
if (rawData.keywords?.tags){
return rawData.keywords?.tags.filter(tag => tag.type === type);
}
return undefined
}
rawData is a messy blob of whatever that is sent to us by another team. We cannot change it. However, we know that there may be the key in it tags
that contains another messy blob of stuff that requires further processing.
How do I get this to build in TypeScript?
I get the following error:
TS7006: Parameter 'tag' implicitly has an 'any' type.
You can add an ad hoc type to rawData
based on what you know about it so far, and maybe improve it over time.
export const getTagsByType = <Data extends { keywords?: { tags: { type: string }[] } }>(type: string, rawData: Data) => {
return rawData.keywords?.tags.filter((tag) => tag.type === type);
}
Note: the if
conditional is not needed as the null coalescing operator would evaluate to undefined
if the condition is not met