Recently I toggle TSConfig property suppressImplicitAnyIndexErrors from true
to false
to force me to write better code, but I encounter this issue that is the only one I wasn't able to fix.
It's a simple form with a checkbox and a text input that will add a true
to filters
in case that the checkbox is checked or delete the property if it existed in case it is false
. The search string is also added if there is any text, if not is deleted as with the checkbox property.
interface UserFilters {
searchText?: string;
hasAction?: boolean;
}
const filters = {} as UserFilters;
function filterUsers(filterName: keyof UserFilters, value: string | boolean | undefined) {
if (value) filters[filterName] = value; // ERROR: Type 'string' is not assignable to type 'undefined'
else delete filters[filterName];
}
I did this TypeScript playground to show you the error.
CodePudding user response:
The problem with filterUsers
is that filterName
and value
are not related in any way, so for example filterUsers('searchText', true)
would be a valid call. That's also why you can't make the types work in the body.
You can fix it by making the function generic:
function filterUsers<K extends keyof UserFilters>(
filterName: K,
value: UserFilters[K],
) {
if (value) filters[filterName] = value
else delete filters[filterName]
}