When developing applications in react and typescript, I find myself frequently creating helper functions. However, there are two key points that always give me pause. One of my functions is provided below, showcasing the common dilemmas I face.
- What should be the return type?
- Is it necessary to validate the parameter types?
Take a look at one of my functions:
interface replacementMap {
key: string,
value: string
} // ex [{key: '[last]', value: 'Washington'}, {key: '[first]', value: 'George'}]
type templateString = string // ex `[last], [first]`
const replaceStringsInTemplate = (m: Array<replacementMap>, t: templateString): (string | null) => {
// Should I do checks like this? I usually do, but is it a waste of time or is
// there a better way to do it?
if (typeof t !== 'string') return null
if (!Array.isArray(m)) return null
let rtn = t;
m.forEach((v) => {
rtn = rtn.split(v.key).join(m.value)
}
return rtn;
}
While I have posed some questions within the code comments, I am still uncertain about whether performing short circuit checks on parameter types is good practice in the function above. Shouldn't typescript catch any errors regarding incorrect types from consumers?
Furthermore, what would be the appropriate return value if a type check fails? I opted for null instead of an empty string, as it felt more fitting. Thoughts?