【问题标题】:Extend a type from a node package从节点包扩展类型
【发布时间】:2021-03-06 13:37:16
【问题描述】:

如何在不修改 @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”、“类型中缺少属性但类型中需要属性”

【问题讨论】:

    标签: node.js reactjs typescript


    【解决方案1】:

    您可以只覆盖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 }
    

    【讨论】:

      猜你喜欢
      • 2021-06-20
      • 2017-11-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 2019-01-02
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      相关资源
      最近更新 更多