I have an interface using TypeScript’s ReturnType
to properly set the type of a value that is determined from the returned type of a function. The function has a specific return type.
Strangely, the type (when I hover over it in VS Code) is any
– see SomeInterface.hasAnyType
in the example code below.
I can’t seem to reproduce this though with my own function, eg SomeInterface.hasAType
in the code below. It only happens when I use createSolanaRpcFromTransport()
(to reiterate, that function does have a return type). I suspect it may be related to createSolanaRpcFromTransport()
using generics. But I’d really like to avoid the type being any
here and fix the problem.
Why does my interface using ReturnType have ‘any’ as a type?
import { createSolanaRpcFromTransport } from "@solana/web3.js";
const sayHello = () => {
return "Hello";
};
interface SomeInterface {
// This uses ReturnType, and has 'string' for a type. Great!
hasAType: ReturnType<typeof sayHello>;
// This also uses ReturnType, but has 'any' for a type. Why?
hasAnyType: ReturnType<typeof createSolanaRpcFromTransport>;
}
Screenshot of VS Code showing SomeInterface.hasAnyType
has any
as a type:
Update: some further testing show the any
goes away if I don’t use ReturnType
and paste the return type of createSolanaRpcFromTransport()
:
import {
RpcFromTransport,
SolanaRpcApiFromTransport,
RpcTransport,
} from "@solana/web3.js";
...
interface SomeInterface {
...
// Now this actually has a type!
hasAnyType: RpcFromTransport<SolanaRpcApiFromTransport<RpcTransport>, RpcTransport>; // ReturnType<typeof createSolanaRpcFromTransport>;
}
However it would nice to use ReturnType
and not have to repeat the type information for createSolanaRpcFromTransport()
.
Update: As requested, info from createSolanaRpcFromTransport hover:
(alias) function createSolanaRpcFromTransport<TTransport extends RpcTransport>(transport: TTransport): RpcFromTransport<SolanaRpcApiFromTransport<TTransport>, TTransport>
import createSolanaRpcFromTransport
Creates a new Solana RPC using a custom transport.
or as a screenshot:
7