【问题标题】:TypeScript type discriminated unions in function arguments函数参数中的 TypeScript 类型区分联合
【发布时间】:2022-01-25 02:41:11
【问题描述】:

函数的第二个参数的类型取决于第一个参数的字符串值。我想得到这样的东西:

    async action (name: 'create', args: { table: string, object: StorageObject }): Promise<StorageObject>;
    async action (name: 'createOrUpdate', args: { table: string, query: StorageQuery, object: StorageObject }): Promise<Array<StorageObject>>;
    async action (name: 'read', args: { table: string, query: StorageQuery }): Promise<Array<StorageObject>>;
    async action (name: 'update', args: { table: string, query: StorageQuery, object: StorageObject }): Promise<Array<StorageObject>>;
    async action (name: 'delete', args: { table: string, query: StorageQuery }): Promise<Array<StorageObject>> {
        ...
    }

目前,我有:TS2394: This overload signature is not compatible with its implementation signature.

【问题讨论】:

标签: typescript types


【解决方案1】:

当您进行重载时,实现签名需要与每个重载兼容。顺便说一句,最后一个签名不会暴露在.d.ts

  async action(name: 'create', args: { table: string, object: StorageObject }): Promise<StorageObject>;
  async action(name: 'createOrUpdate', args: { table: string, query: StorageQuery, object: StorageObject }): Promise<Array<StorageObject>>;
  async action(name: 'read', args: { table: string, query: StorageQuery }): Promise<Array<StorageObject>>;
  async action(name: 'update', args: { table: string, query: StorageQuery, object: StorageObject }): Promise<Array<StorageObject>>;
  async action(name: 'delete', args: { table: string, query: StorageQuery }): Promise<Array<StorageObject>>;

  // The actual implementation that needs to cover every case above 
  async action(name: 'create' | 'delete' | 'update' | 'read' | 'createOrUpdate', args: { table: string, query: StorageQuery, object: StorageObject }): Promise<Array<StorageObject> | StorageObject> {
    if (name === 'create' || name === 'delete') {
      return Promise.resolve(new StorageObject())
    }

    return Promise.resolve([new StorageObject()])
  }

Playground

【讨论】:

    猜你喜欢
    • 2017-04-10
    • 2020-02-25
    • 2020-02-16
    • 2021-02-21
    • 2021-04-19
    • 2021-07-22
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多