Typescript函数使用类型文字重载

问题描述 投票:0回答:1

我想用打字稿中的命名参数定义一个重载函数。将执行以下代码,但会向我显示功能签名之一中不存在的init.index警告。

我想重载的原因是,在docs中定义的对象上提供互斥属性,但在官方library中未定义。

export function insertText(init: { text: string, index: number }): docs_v1.Schema$Request;
export function insertText(init: { text: string, segmentId?: string }): docs_v1.Schema$Request {
  return {
    insertText: {
      text: init.text,
      ...(init.index && { location: { index: init.index } }),
      ...(!init.index && { endOfSegmentLocation: { segmentId: init.segmentId } }),
    }
  }
}

我提供了typescript playground并提供了示例代码和我看到的错误。

此外,我想按照here的描述来分解对象参数。

typescript google-docs-api
1个回答
1
投票

我认为您的示例在单个重载和联合的情况下会更好。如果您拥有工会,您唯一需要做的就是以某种方式区分这些值。

一个选择是使用in字体保护器:

export function insertText(init: { text: string, index: number } | { text: string, segmentId?: string }): docs_v1.Schema$Request {
  return {
    insertText: {
      text: init.text,
      ...('index' in init && { location: { index: init.index } }),
      ...(!('index' in init) && { endOfSegmentLocation: { segmentId: init.segmentId } }),
    }
  }
}

Play

或者,如果您在联合中的两个选项中都添加了index,但是如果额外的index定义的类型为null | undefined,您也可以使用== null

export namespace docs_v1 { export interface Schema$Request {}; };

// Provided example
export function insertText(init: { text: string, index: number } | { text: string, index?: undefined | null; segmentId?: string }): docs_v1.Schema$Request {
  return {
    insertText: {
      text: init.text,
      ...(init.index != null && { location: { index: init.index } }),
      ...(init.index == null && { endOfSegmentLocation: { segmentId: init.segmentId } }),
    }
  }
}

Play

© www.soinside.com 2019 - 2024. All rights reserved.