DefaultValue type forcing me to check the type before using the property
See original GitHub issueI think this issue should be addressed by @csantos42’s DefinitelyTyped, but I’m not sure where to submit this issue. If anyone could point me out where should be best I will be glad.
In this example I have the usage of a selector called “userState” that uses a atom called “userAtom” and it’s function is to save a cache from the atom new value on localStorage and saves a bearer token inside Axios default header Authorization:
export const userState = selector<IUser | null>({
key: "userState",
get: ({ get }) => {
return get(userAtom);
},
set: ({ set }, user) => {
if (user !== null) {
Axios.defaults.headers.Authorization = `Bearer ${user.token}`;
localStorage.setItem(ls("userState"), JSON.stringify(user));
} else {
localStorage.removeItem(ls("userState"));
}
set(userAtom, user);
},
});
The problem is that TypeScript is complaining that “token” used here is not a DefaultValue’s property:
Axios.defaults.headers.Authorization = `Bearer ${user.token}`;
TS2339: Property 'token' does not exist on type 'DefaultValue | IUser'. Property 'token' does not exist on type 'DefaultValue'.
But I expect that TypeScript only checks the type I informed here:
export const userState = selector<IUser | null>({
My suggestion is to change this type:
export interface ReadWriteSelectorOptions<T> extends ReadOnlySelectorOptions<T> {
set: (
opts: {
set: SetRecoilState;
get: GetRecoilValue;
reset: ResetRecoilState;
},
newValue: T | DefaultValue,
) => void;
}
to
export interface ReadWriteSelectorOptions<T = DefaultValue> extends ReadOnlySelectorOptions<T> {
set: (
opts: {
set: SetRecoilState;
get: GetRecoilValue;
reset: ResetRecoilState;
},
newValue: T,
) => void;
}
Then the DefaultValue type is only used when I don’t inform any type to the selector usage.
For now my workaround was to check the value’s type:
if (!(user instanceof DefaultValue)) {
Axios.defaults.headers.Authorization = `Bearer ${user.token}`;
}
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:6 (3 by maintainers)
Top GitHub Comments
If you’re using typesctipt, you can use the following (guard)
This is how you use it:
I bumped into the same problem and used ‘as’ to type cast the value, if you do not want to reset the selector with DefaultValue