Conversation
| export type ReactChildren = React.ReactNode; | ||
|
|
||
| export type ToastType = string; | ||
| export type ToastType = 'success' | 'error' | 'info' | string; |
There was a problem hiding this comment.
Hi @ShivamJoker, unfortunately this does not help: adding | string at the end widens the type of ToastType to string.
There was a problem hiding this comment.
@calintamas there should be some way to have all the types ?
There was a problem hiding this comment.
I suppose it should dynamically extract all the possible types from the config prop
There was a problem hiding this comment.
No it doesn't give any auto completion
There was a problem hiding this comment.
Indeed, it's implemented as a simple string at this point. I was just suggesting how I think it can be improved
There was a problem hiding this comment.
You know what I mean?
ToastType to be dynamically computed based on the config prop.
For example:
const toastConfig = {
foo: () => {},
bar: () => {},
baz: () => {}
}
<Toast config={toastConfig} />Would result in:
export type ToastType = 'success' | 'error' | 'info' | 'foo' | 'bar' | 'baz';There was a problem hiding this comment.
Oh I see! Here is the issue which I was going through to see if we can do anything about it microsoft/TypeScript#29729
I am not sure how will we dynamically generate it, but in redux toolkit they are using some stuffs to do dynamically generate types.
There was a problem hiding this comment.
A solution would be to take a generic.
type ToastTypes = 'success' | 'error' | 'notification';
const toastConfig: ToastConfig<ToastTypes> = {
success: () => {},
error: () => {},
notification: () => {}
}
<Toast<ToastTypes> config={toastConfig} />ToastConfig would then be
type ToastConfig<ToastTypes extends *something to ensure it is a string union*> = {
[key: ToastTypes]: (params: ToastConfigParams<any>) => React.ReactNode;
};But this doesn't really solve the Toast.show() autocomplete.
An other way would be to allow users to extends the type of the library as I do with react-navigation:
// Globally type react-navigation
declare global {
// eslint-disable-next-line @typescript-eslint/no-namespace
namespace ReactNavigation {
interface RootParamList extends RoutesParams {}
}
}On this example I set the global RootParamList to my RoutesParams so my navigation.navigate() have proper autocomplete.
An other way to do this without global types editing is to hint the user to make a wrapper. They create the following function with the generic I proposed above:
export function toastShow(arg) {
return Toast.show<ToastTypes>(arg);
}This wrapper only provide the type, as we could do with useNavigation without editing the global types:
export function useNavigation() {
return useNavigation<MyNavigationTypes>();
}
It adds types in the toastType for error, success and info rather than just string