I want to write a function that converts a specific value in an object from string to a number.
Here is my function:
export function convertStringToNumber<K extends string>(
obj: Record<K, object>,
val: string
): Record<K, number> {
const result: Partial<Record<K, unknown>> = {}
for (const key in obj) {
if (key === val) {
result[key] = Number(obj[key])
} else {
result[key] = obj[key]
}
}
return result as Record<K, number>
}
My function is working, but my TypeScript is complaining about the types. Can TypeScript take the input types and just change the type of an appropriate key to a number?
I have a second version, perhaps this one is more appropriate:
export function convertStringToNumber2<T> (
obj: T,
val: string
): T {
const result: Partial<T> = {}
for (const key in obj) {
if (key === val) {
result[key] = Number(obj[key])
} else {
result[key] = obj[key]
}
}
return result
}
TypeScript is complaining: Type 'number' is not assignable to type 'T[Extract<keyof T, string>]'.ts(2322)