Tengo un componente de flujo de control con React que
children cuando la condición es true ,null o una alternativa si la condición es false interface Props { when: boolean fallback?: () => JSX.Element children: Children } export const Show = ({ when, fallback, children }: Props) => { if (!when) return <>{fallback?.() || null}</> return <>{children}</> }si no uso este componente y uso un operador binario simple, TypeScript funciona muy bien:
interface Props { value: {nested: string} | null } const SomeComponent =({value}:Props)=>( <div> {value && ( <div> {value.nested} value is inferred the type "{nested: string}" </div> )} </div>Si uso el componente de flujo de control, el tipo no se infiere y mecanografiado da un error:
interface Props { value: {nested: string} | null } const SomeComponent =({value}:Props)=>( <div> <Show when={!!value}> <div> {value?.nested} typeof value remains "{nested: string} | null", therefore I need some conditional chaining </div> </Show> </div>¿Alguna idea sobre cómo hacer que la inferencia de tipos funcione?
No puede hacerlo de esta manera, porque el código dentro de <Show></Show> en realidad se ejecuta antes de que Show tenga la oportunidad de evitar que se represente el div . Piense en lo que sucede cuando JSX se transpila a javascript:
React.createElement( Show, {when: !!value}, React.createElement( 'div', {}, `${value?.nested} typeof value remains "{nested: string} | null", therefore I need some conditional chaining` ) )¿Ves el problema? Si lo reescribimos un poco:
const textContent = `${value?.nested} typeof value remains "{nested: string} | null", therefore I need some conditional chaining` React.createElement( Show, {when: !!value}, React.createElement( 'div', {}, textContent ) ) Estos fragmentos son exactamente iguales, y en ambos value?.nested se evalúa antes de que Show incluso se procese. No puedo recomendarle ninguna buena solución aquí, tal vez algo como esto:
interface Props<T> { value: T fallback?: () => JSX.Element children: (value: T) => ReactNode } export const CheckExists = <T extends any>({ value, fallback, children }: Props<T>) => { if (!value) return fallback ? fallback() : null return <>{children(value)}</> } <CheckExists value={value}> {existingValue => ( <div>{existingValue.nested}</div> )} </CheckExists>Pero esta es una interfaz diferente y puede no ser adecuada para usted