Untitled

 avatar
unknown
typescript
a year ago
1.4 kB
9
Indexable
// WHAT I PROPOSED
interface PaymentAppContextType {
  propA: string;
  propB: number;
}

export const PaymentAppContext = createContext<PaymentAppContextType | undefined>(undefined);

export const PaymentAppProvider: React.FC<{ value: PaymentAppContextType }> = ({ children, value }) => {
  return <PaymentAppContext.Provider value={value}>{children}</PaymentAppContext.Provider>;
};

export const usePaymentAppContext = () => {
  const context = useContext(PaymentAppContext);
  if (context === undefined) {
    throw new Error('usePaymentAppContext must be used within a PaymentAppProvider');
  }
  return context;
};

// then the use is as follows

const MyComponent = () => {
    const { propA } = usePaymentAppContext()
}


/// WHAT KONRAD WANTS TO ENFORCE
interface PaymentAppContextType {
  propA: string;
  propB: number;
}

// notice the null as unknown as 
export const PaymentAppContext = createContext<null as unknown as PaymentAppContextType>(undefined);

export const PaymentAppProvider: React.FC<{ value: PaymentAppContextType }> = ({ children, value }) => {
  return <PaymentAppContext.Provider value={value}>{children}</PaymentAppContext.Provider>;
};

// the usage
const MyComponent = () => {
    // let's notice here that, the return from the useContext may yield broken values
    // as the PaymentAppContext value may be null, if it wasn't provided.
    const { propA } = useContext(PaymentAppContext)
}
Editor is loading...
Leave a Comment