I have a personal rule of thumb: we should always prioritize less manual types and more inferred types whenever possible.
But there are cases that can be tricky. For example: inferring state from initial props.
It’s very common to separate the types specially when you are dealing with optional/nullable properties and it will be initiated as
It’s very common to separate the types specially when you are dealing with optional/nullable properties and it will be initiated as
undefined or null, as shown below:type ContextProps = {
current: string | undefined;
pagination: { current: number; total: number };
finished: boolean;
prev: string | undefined;
next: string | undefined;
goNext: (() => void) | undefined;
goPrev: (() => void) | undefined;
}
const Context = React.createContext<ContextProps>({
current: steps[0],
pagination: { current: 1, total: steps.length },
finished: false,
prev: undefined,
next: undefined,
goNext: undefined,
goPrev: undefined,
});
But you don’t have to! You can benefit from using
as to indicate that the prop can be of a type other than undefined or nullconst Context = React.createContext({
current: steps[0],
pagination: { current: 1, total: steps.length },
finished: false,
prev: undefined as string | undefined,
next: undefined as string | undefined,
goNext: undefined as (() => void) | undefined,
goPrev: undefined as (() => void) | undefined,
});
// If you need props later
type ContextProps = React.ContextType<typeof Context>;