I've got a function to strip null bytes from strings in input data:
export function stripNullBytes(str: string | null): string | null {
return str?.replace(/\0/g, '') ?? null
}
Some of my input strings can be null, and some can't be (they're coming from a database). Similarly, some of the output strings can be null, and some can't be.
If I call stripNullBytes on one of the strings that can't be null (and so the output can't be null either), Typescript complains that stripNullBytes(cantBeNull) is not of the right type (it's string | null instead of string).
Is there a way I can tell TypeScript this fact about my function? I can use the bang operator (let str: string = stripNullBytes(cantBeNull)!), but is there a more elegant way that removes the possibility of me making a mistake?
(str: string) => string | (str: null) => null, rather than(str: string | null) => string | null? Have you tried overloads?