I have two TypeScript examples where I’m trying to ensure that a parameter type (Param) is inferred as string. In the first example, it works as expected, but in the second, it does not. Here are the details:
Working Case
class Chat<T> {
constructor(private adapter: BaseChatAdapter<T>) {}
send(message: T) {}
}
interface BaseChatAdapter<T> {
send(message: T): void;
}
class StringAdapter<T = string> implements BaseChatAdapter<T> {
send(message: T) {}
}
const c = new Chat(new StringAdapter());
type Param = Parameters<typeof c['send']>[0]; // Param is inferred as string
Non-working Case
class Chat<T> {
constructor(private adapter: BaseChatAdapter<T>) {}
send(message: T) {}
}
interface BaseChatAdapter<T> {
// The 'send' method is removed
}
class StringAdapter<T = string> implements BaseChatAdapter<T> {
send(message: T) {}
}
const c = new Chat(new StringAdapter());
type Param = Parameters<typeof c['send']>[0]; // Param is inferred as {}
In the second example, Param is inferred as {}, even though I expect it to be string. The only difference between the two cases is the commented-out send method in the BaseChatAdapter interface.
Questions:
-
Why does the absence of the send method in the BaseChatAdapter interface affect the type inference in the second example?
-
Is there a way to ensure Param is correctly inferred as string in the second case without explicitly defining the method in the interface?
Any insights or explanations would be greatly appreciated!