DEV Community

Discussion on: Getting started with Vue 3 + Pinia Store + TypeScript by building a Grocery List App

Collapse
 
cefn profile image
Cefn Hoile

Hi, Carlo. Thought it was worth pointing out a latent bug in the example. Probably as RootState should never be used. You can see and experiment with the error at tsplay.dev/WkM3lN

Essentially the clause as RootState is a type assertion, when what is probably intended is for that data structure to be validated as a RootState by the compiler. Normally the keywords as and any are a sign types are being bypassed (with the exception of as const).

The type assertion is hiding an error in the stateFactory2 example below, but the compiler can't pick that up, since you have asserted the type and hence suspended the validation of the compiler.

The example stateFactory3 below is preferred, and DOES reveal the bug as a compiler error.

interface RootState {
    message:string|null
}
const stateFactory1 = () => ({message:null} as RootState);
const stateFactory2 = () => ({message:"something", hmm:4} as RootState);
const stateFactory3 = (): RootState => ({message:"something", hmm:4});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
carlomigueldy profile image
Carlo Miguel Dy

Hey Cefn, thank you so much for pointing this out! I haven't actually gotten into details regarding this so I highly appreciate your comment as it helps out for the other readers as well