setStore TypeScript Issue
I have a object store that has an interface like this:
type1 looks like this:
type2 looks like this:
Now I have a components where I pass in the following props struct
Within the component I make calls like:
(where props.id = "object1" or "object2")
These do not create any typescript error.
When I make a call like this:
(where props.id = "object2")
I get an error like this:
The code runs fine without error, so I feel like I am not actually using setStore incorrectly.
Why doesn't TypeScript recognize "invert" as valid Part in this situation? Is there any way I can fix this without supressing the TypeScript error?
11 Replies
Part<type1| type2, "channel" | "role" | "value">
… suggests to me that problem is inside the Part<T,K>
type- I'm noticing how the second union only lists types that are shared between type1
and type2
; role
is in that union, invert
is not.Yeah, I noticed that too. I do not however know enough to say if this issue is a bug or not. Perhaps i will make an issue on the repo and see what people have to say.
here is a full example of the error:
I am thinking that I may have to narrow the Part<T,K> to the specific interface being passed through. I don't know how to do that though.
TypeScript needs more help to understand your types:
Always keep in mind that TypeScript is structurally typed, not nominally typed.
I guess I don't understand why doing something like this:
Doesn't work.
That is generally the behavior I want, but I don't know how to write KeysOfType to make that happen, or even if it is possible.
Interesting. If I remove the optional attribute from the interfaces I can have it like that.
Perhaps you would be more comfortable with
With conditional types
extends
simply means:
the type on the left of is assignable to the one on the right.if you look at your definition … … where you have elected to make all members optional. Consequently: Perhaps you would be shocked to realize: Object assignment is not subject to excess property checking. Hence my warning about structural typing.
Documentation - Conditional Types
Create types which act like if statements in the type system.
TS Playground - An online editor for exploring TypeScript and JavaS...
The Playground lets you write TypeScript or JavaScript online in a safe and sharable way.
Ah that makes sense. I think I may need to take a different approach to the structure of my project to avoid this. Thanks for all the help.
Documentation - TypeScript for Functional Programmers
Learn TypeScript if you have a background in functional programming
It was simple enough to make the extends condition not be true for my application.
Works great after making the types be incompatible with one another. Thanks again for all of your insight.