I am having a problem on typing a helper. My goal is to replace null values in an object with an empty string while maintaining my key values relationships in typescript
// from
{
name: string | undefined
url: string | null | undefined
icon: string | null | undefined
}
// to
{
name: string | undefined
url: string | undefined
icon: string | undefined
}
For this I use a mapObjIndexed
from Ramda to replace each null
by ''
nothing complicated
const mapObjIndexed = (callBack, values) => {
Object.fromEntries(
Object.entries(values).map(entries => [
entries[0],
callBack(entries[1])
])
)
}
Let’s show you my problem
import { mapObjIndexed } from "ramda"
// helper
const types = {
isNull: (value: any): value is null => value === null
}
// test 1 => ts error
const nullToEmptyString = <T>(value: T | null): T | '' => types.isNull(value) ? '' : value
// test 2 => ts error
const nullToEmptyString2 = <T extends any>(value: T): T extends null ? '' : T => types.isNull(value) ? '' : value
// parser => ts error
const nullsToEmptyStrings = <T>(value: { [K in keyof T]: T[K] | null }): { [K in keyof T]: T[K] | '' } => mapObjIndexed(nullToEmptyString, value)
The only way to make it work is to force the return values with as
I can’t find any solution and my level in Typescript does not allow me to do it