V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
TWorldIsNButThis
V2EX  ›  TypeScript

typescript 类型的交并运算问题,官方文档好像也没给交并运算的详细信息,就给了一个基本的用法

  •  
  •   TWorldIsNButThis · 2022-06-07 12:14:05 +08:00 · 1054 次点击
    这是一个创建于 679 天前的主题,其中的信息可能已经有所发展或是发生改变。
    type IssueExcludeAssigneesField = {
      id: number
      project_id: number
      title: string
      due_date: string | null
    }
    type Assignee = {
      name: string
    }
    
    type Issue = IssueExcludeAssigneesField & ({ assignees: [Assignee] } | { assignees: [] })
    type Issue2 = IssueExcludeAssigneesField & { assignees: [Assignee] | [] }
    
    
    declare function map<T1, T2>(_: (_: T1) => T2): T2
    declare function pick<T>(_: T): Pick<T, keyof T>
    
    map<Issue, Issue>(pick)  // Type '[Assignee]' is not assignable to type '[]'.
    map<Issue2, Issue2>(pick) // OK
    
    declare function mapIssue(_: Issue): Issue2
    map<Issue, Issue>(mapIssue) // OK
    
    type assignees1 = Issue['assignees']
    type assignees2 = Issue2['assignees']
    declare function mapAssignee(_: assignees1): assignees2
    map<assignees1, assignees1>(mapAssignee) // OK
    

    playground

    上面的这段代码为啥第一个 pick 会报错
    后面的两个 map 应该能证明两个 issue 和 assignees 都是可以互相赋值的等价的类型吧

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1175 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 23:05 · PVG 07:05 · LAX 16:05 · JFK 19:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.