![](/img/trans.png)
[英]Extend @types/node with custom project environment variable type decelerations
[英]Extend a type from a node package
如何在不修改 @types 文件的情况下从节点包中扩展类型?
import { Session, useSession } from 'next-auth/client'
// I AM TRYING TO EXTEND THE Session TYPE
export default function Component() {
// useSession() returns type-> useSession(): [Session, boolean]
const [session]: [<ENTER EXTENDED TYPE HERE>, boolean] = useSession()
...
}
来自@types/next-auth
type Session = SessionBase & GenericObject;
interface SessionBase {
user: User;
accessToken?: string;
expires: string;
}
interface User {
name?: string | null;
email?: string | null;
image?: string | null;
}
结果应该是这样的类型:
type NewSession = NewSessionBase & Session;
interface NewSessionBase {
user: {
name?: string | null;
email?: string | null;
image?: string | null;
myCustomData?: {
uid: string | null;
}
};
accessToken?: string;
expires: string;
}
这将修复错误:“TS2741”,“属性缺少类型但类型需要”
您可以只覆盖Session
类型的user
属性。
type GenericObject = {}
type Session = SessionBase & GenericObject;
interface SessionBase {
user: User;
accessToken?: string;
expires: string;
}
interface User {
name?: string | null;
email?: string | null;
image?: string | null;
}
type NewSession = NewSessionBase & Session;
type NewUser = {
name?: string | null;
email?: string | null;
image?: string | null;
myCustomData?: {
uid: string | null;
}
}
interface NewSessionBase {
user: NewUser;
accessToken?: string;
expires: string;
}
// The main part of answer
type ExtendedSession = Session & {user: NewUser};
这是用另一种属性替换一种类型的属性的更奇特的方式。 如果您有更复杂的替换逻辑,您可以使用它
type Replace<Obj, Property extends keyof Obj, NewType> = {
[P in keyof Obj]: P extends Property ? NewType : Obj[P]
}
type Foo = Replace<{ expires: string }, 'expires', number> // { expires: number }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.