Hello everyone,
I am playing around with typescript and I am stuck on how to infer the type of an object, here is what my code looks like:
class Responnse<Context = null> {
private context: Context | null = null;
constructor(props?: { createContext?: () => Context }) {
if (props && props.createContext) {
this.context = props.createContext();
}
}
public middleware = (
cb: ({
context,
}: {
context: //What type should go there ?, so that context from the consumer is infered
Context;
}) => void,
) => {
// getting a ts error over here see the ts playground for more context.
cb({ context: this.context });
return this;
};
}
The consumer code:
const updateWhatever = () =>
new Responnse({
//optional createContext function. if createContext function is not there, then the context should be infered as null,
// if its there then context should be the return type of this function
createContext: () => {
return {
name: "micheal?",
};
},
})
.middleware(({ context }) => {
//the context object here should be infered as {name:string} because the createContext return {name:'micheal'}
console.log("start");
})
If you need anything else please let me know.