How to use Typescript on runtimeModel in contextStore? #947
-
I can't figure out how to properly define type for runtimeModel. Currently I just use type RuntimeModel = {
myProp: string,
}
export const MyContextStore = createContextStore<RuntimeModel>((runtimeModel)=> ({
// @ts-ignore
myProp: runtimeModel.myProp,
})) My main concern is the undefined part in Any advice? Whatever I try I get some errors 😞 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
The Instead of using
export const MyContextStore = createContextStore<RuntimeModel>((runtimeModel)=> ({
myProp: runtimeModel?.myProp ?? 'fallback',
}))
export const MyContextStore = createContextStore<RuntimeModel>((runtimeModel)=> ({
myProp: runtimeModel!.myProp,
}))
export const MyContextStore = createContextStore<RuntimeModel>((runtimeModel)=> {
if(runtimeModel === undefined) {
throw new Error("runtimeModel is required");
}
return {
// 👇 not undefined anymore
myProp: runtimeModel.myProp,
}
}) Hope that helps 👍 |
Beta Was this translation helpful? Give feedback.
The
runtimeModel
argument isRuntimeModel | undefined
because it's not guaranteed to be set. In other words, theruntimeModel
property on theMyContextStore.Provider
is optional, so it has to be defined asRuntimeModel | undefined
.Instead of using
@ts-ignore
, you have some options: