0

I have the following key-value pair and it is being used for a filtering system. When we apply a filter, we could merge it with all the current ones, or just apply it with resetting the previous.

type MINE = "mine"
type BOOKMARKED = "bookmarked"
type TEXT_QUERY = "textQuery"
type JobType = "type"

export type PossibleFilterKeys = MINE | BOOKMARKED | TEXT_QUERY | JobType

type Filter = {
    [key in PossibleFilterKeys]: string;
};

Then I have the following prototype of a function:

const apply = (filter: Filter) => void

When we use it:

// name: PossibleFilterKeys,
// value: string,
apply({[name]: value})

It triggers: TS2345: Argument of type '{ [x: string]: string; }' is not assignable to parameter of type 'Filter'.   Type '{ [x: string]: string; }' is missing the following properties from type 'Filter': mine, bookmarked, textQuery, type

I want to apply a filter, its key could be one of the PossibleFilterKeys type, but it throws the error above.

Why does this happen?

2
  • please share reproducable example Commented Mar 22, 2021 at 9:33
  • Thanks to @31piy the problem was solved. As he said, we could do: [key in PossibleFilterKeys]?: string but we also can use the Partial utility: apply: (filter: Partial<Filter>) => void Commented Mar 22, 2021 at 9:49

1 Answer 1

4

The issue is with this statement:

type Filter = {
    [key in PossibleFilterKeys]: string;
};

The above declares that Filter must contain all the keys of PossibleFilterKeys. You can make those optional by the following syntax:

type Filter = {
    [key in PossibleFilterKeys]?: string; // <-- Place a question mark
};
Sign up to request clarification or add additional context in comments.

3 Comments

Yeah it works, thank you! Another way is: apply: (filter: Partial<Filter>) => void
@Stephan882 -- I don't think that's a good choice. Your way just solves one part, i.e. to call the function with a partial object. What about creating the Filter objects? Those still require all the keys.
Well, you are right. Currently I'm not creating anything. We call the function, pass an object, and merge or replace the current one. Thank you again, I do really appreciate your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.