In my app, I require an object that can store strings or an array of strings with a string key. This object will serve as a dynamic configuration and the keys will be defined by the user, so I cannot specify types based on key names. That's why I'm using index signatures to accommodate any type of key. The values will consist of arrays in one part of the app and strings in another.
As I try to implement this, I encounter errors indicating that TypeScript is unable to differentiate between a string and an array of strings:
type FiltersStateType = {
filters: { [key: string]: Array<string> | string }
}
const example: FiltersStateType = {
filters: {
sandwiches: ['ham', 'cheese'],
milkshakes: ['choc', 'banana'],
randomString: 'hello',
},
}
example.filters.sandwiches.filter(item => item !== 'ham')
// ❌ Property 'filter' does not exist on type 'string | string[]'.
// ❌ Property 'filter' does not exist on type 'string'
// do I need to type narrow every time to discern between string and string[]?
if (Array.isArray(example.filters.sandwiches)) {
example.filters.sandwiches.filter(item => item !== 'ham')
}
This issue arises because TypeScript struggles to determine if the value is a string or an array. Do I have to explicitly narrow down the type each time to differentiate between a string and an array of strings?
if (Array.isArray(example.filters.sandwiches)) {
example.filters.sandwiches.filter(item => item !== 'ham')
}