[英]TypeScript obtain type for class instance
I'm using a library that exposes an SDK, but not the type ( UserModule
) of one of the objects ( user
) you can create with it.我正在使用一个库,该库公开了 SDK,但不是您可以使用它创建的对象(
user
)之一的类型( UserModule
)。
import { Magic } from 'magic-sdk';
// ...
function useMagicLinkAuthentication() {
const [magicReady, setMagicReady] = usePromise<Magic>();
const [isMagicInitialized, setMagicInitialized] = useState(false);
const [user, setUser] = useState<UserModule | null>(null);
// ...
const signIn = async (email: string) => {
const magic = await magicReady;
if (await magic.user.isLoggedIn()) {
return setUser(magic.user);
}
await magic.auth.loginWithMagicLink({ email });
return setUser(magic.user);
};
// ...
}
As you can see, I need access to the UserModule
in useState
which I have no access to (because I can't do import { UserModule } from 'magic-sdk';
.如您所见,我需要访问我无权访问的
UserModule
中的useState
(因为我无法import { UserModule } from 'magic-sdk';
。
For functions there is ReturnType
.对于函数,有
ReturnType
。 So if I have a regular function, I can do:所以如果我有一个普通的 function,我可以这样做:
export const createFoo = () => { /* ... returns a Foo ... */ }
export type Foo = ReturnType<typeof createFoo>;
Is there an equivalent for classes in TypeScript so that I can access the instance of new MyClass
and get TypeScript 中的类是否有等效项,以便我可以访问
new MyClass
的实例并获取
// broken pseudo-code
export type Foo = Something<typeof MyClass.foo>
? ?
I need to somehow get typeof magic.user
aka the UserModule
type.我需要以某种方式获取
typeof magic.user
又名UserModule
类型。
You can use a type
alias from the constructor:您可以使用构造函数中的
type
别名:
type UserModule = Magic['user'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.