I have a function that parses a string into a value and returns a default value if it fails. The issue is that this code returns too strict types for primitives, such as `false` instead of `boolean`. How can I resolve this? Should I utilize some form of casting for the `defaultValue` parameter? Thank you in advance.
export function safeParse<T>(text: string, defaultValue?: T): T | undefined {
try {
return JSON.parse(text);
} catch {
return defaultValue; // Is there a need for any type cast here?
}
}
const res1 = safeParse('128', 0); // typeof res1 is '0 | undefined'
const res2 = safeParse<number>('128', 0); // OK: typeof res2 is 'number | undefined'
const res3 = safeParse('128', 0 as number); // OK: typeof res3 is 'number | undefined'