'Is there a way to remove all occurrences of the "__typename" property in Typescript?
I want to remove all occurrences of "__typename" from dictionary "data". I used one of the function from this stackoverflow post: How to remove all instances of a specific key in an object? and it outputs the correct answer but my compiler displays this error message. I am new to Typescript and I am having a hard time finding a solution.
Code snippet:
import * as R from ramda;
// Dictionary "data"
const data = {
"subscription": {
"id": "10",
"subscribers": [
{
"id": "2017",
"username": "potato1",
"__typename": "UserType"
},
],
"unsubscribers": [
{
"id": "2022",
"username": "potato2",
"__typename": "UserType"
}
],
"__typename": "SubscriptionType"
},
"__typename": "Subscribe"
};
// Function from linked stackoverflow post, works but get a syntax error (see screenshot)
const removePropDeep = R.curry((prop, data) =>
R.when(
R.is(Object),
R.pipe(R.dissoc(prop), R.map(removePropDeep(prop))),
data
)
);
console.log(removePropDeep("__typename", data));
Expected:
{
"subscription": {
"id": "10",
"subscribers": [
{
"id": "2017",
"username": "potato1",
},
],
"unsubscribers": [
{
"id": "2022",
"username": "potato2",
}
],
},
};
Error message:
"Function implicitly has return type 'any'
because it does not have a return type annotation
and is referenced directly or indirectly
in one of its return expressions."
Solution 1:[1]
You'll need to create a function overload definition using an interface, because the function is curried. I've used the same definition of R.dissoc (sandbox).
Note: I've replaced R.map with R.mapObjIndexed because TS has a hard time infering that in this case R.map iterates an object.
interface iRemovePropDeep {
<T extends object, K extends keyof T>(prop: K, obj: T): Omit<T, K>;
<K extends string | number>(prop: K): <T extends object>(
obj: T
) => Omit<T, K>;
}
const removePropDeep: iRemovePropDeep = curry((prop, data) =>
when(
is(Object),
pipe(dissoc(prop), mapObjIndexed(removePropDeep(prop))),
data
)
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
