I am currently working on a personalized interface where I aim to determine the type of an interface value within its implementation rather than in the interface definition, without using generics. It is important to note that these implementations will always be in the form of object literals and not classes.
This is what I am attempting to achieve:
interface Defintion {
params: unknown; // should resolve to the type in the implementation
handler: (dummy: this["params"]) => void; // I want `this` to refer to the implementation, not the interface
}
const customDefn: Defintion = {
params: { test: "Hello World" },
handler: (dummy) => {
// TypeScript raises an error here
console.log(dummy.test)
}
}
My goal is for the type of customDefn.params
to be resolved to
{ test: "Hello World" }
(to enable autocomplete in handler
) rather than staying as unknown
.
I acknowledge the option to use generics:
interface Defintion<T> {
params: T;
handler: (dummy: this["params"]) => void;
}
However, I would then need to define params
twice (as I also use params
programmatically):
const customDefn: Defintion<{ test: "Hello World" }> = {
params: { test: "Hello World" },
handler: (dummy) => {
console.log(dummy.test)
}
}
This can quickly become cumbersome.