I am currently working on a function that has the ability to split a string using a specified separator and then convert the values in the resulting array to either strings or numbers based on the value of the convertTo
property.
Even when I call this function with convertTo = 'number'
, TypeScript continues to infer the result as type Array<string | number>
. However, I would prefer it to be recognized as type Array<number>
.
Is there a way to achieve this in TypeScript?
type Options = {
separator?: string;
convertTo?: 'string' | 'number';
};
export function splitAndTrim(value: string, options: Options = {}): Array<string | number> {
const { separator = ',', convertTo = 'string' } = options;
return value.split(separator).map(entry => {
if (convertTo === 'string') {
return entry.trim();
}
return Number(entry);
});
}
// Despite the function performing as expected, the issue lies within TypeScript typings where parsedValue remains as type Array<string | number>.
// Is there a method to change its type to Array<number>? Ideally, I was anticipating TypeScript to automatically infer this.
const parsedValue = splitAndTrim(value, {convertTo: 'number'});
Please note that the function is fully functional, my concern pertains to TypeScript typings.
Any suggestions or guidance would be greatly appreciated!