Narrowing setDiscriminatedValue setter parameter by discriminating discriminatedValue
#3169
-
|
Would this type-narrowing behavior be possible to implement without making a breaking change? type Uninitialized = {
key: "uninitialized",
value?: never
}
type Initialized = {
key: "initialized",
value: string
}
const stateAtom = atom<Uninitialized | Initialized>({
key: "uninitialized"
});
...
// In some React component
const [state, setState] = useAtom(stateAtom);
if (state.key === "uninitialized") {
setState((prev) => {
// prev.key is "uninitialized" | "initialized", but
// we already know it is "uninitialized"
});
}My use case for this would be conditionally rendering something (ie. a button) based on function Page() {
const [state, setState] = useAtom(stateAtom);
// ...
return (
<div>
{state.key === "initialized" &&
<button onClick={
// Behavior I want - currently using a switch statement to throw an error when state.key !== "initialized"
() => setState((prev) => ({ ...prev, value: "value" }))
}>
Set value
</button>
}
</div>
)
} |
Beta Was this translation helpful? Give feedback.
Answered by
dai-shi
Oct 27, 2025
Replies: 1 comment 4 replies
-
|
The solution is just using |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think it's possible in TS in general.