打字稿:基于类型的可选方法参数

时间:2020-09-24 13:45:10

标签: javascript reactjs typescript

我有一个方法,其中id仅在类型B时可用,请看下面

(index: string, type: ResourceType.A, data: any): JSX.Element;

(index: string, type: ResourceType.B, data: any, id: string): JSX.Element;

所以我试图创建一个方法重载为

type IOverload = {
  (index: string, type: ResourceType.A, data: any): JSX.Element;
  (index: string, type: ResourceType.B, data: any, id: string): JSX.Element;
}

现在尝试创建一个方法

const getJsx: IOverload = (
    index: string,
    type: ResourceType.A | ResourceType.B,
    data: any,
    id?: string
  )=> {
.
.
.
type === ResourceType.B ? myFunc(id) : yourFunc(data)
}

并且我的方法myFunc被声明为

const myFunc = (id: string) => {

但是现在我收到如下错误,显示myFunc

Argument of type 'string | undefined' is not assignable to parameter of type 'string'.

请帮助解决此问题,我希望对getJsx进行更改,然后 不想用myFunc声明我的方法string | undefined

const myFunc = (id: string| undefined) => {

3 个答案:

答案 0 :(得分:1)

您可以创建一个重载,如果资源不是Resource.B且有4个参数(Playground),则会引发错误:

enum ResourceType {
  A, B
}

function test(index: string, type: ResourceType.B, data: any, id: string): any;
function test(index: string, type: ResourceType.A, data: any): any;
function test(...args: (string | ResourceType)[]) {
  const index = args[0] as string
  const type = args[1] as ResourceType
  const data = args[2] as any
  const id = args[3] as string | undefined
}

test('abc', ResourceType.A, 'myData', 'myId') // Throws error
test('abc', ResourceType.A, 'myData')         // Accepted

test('abc', ResourceType.B, 'myData', 'myId') // Accepted
test('abc', ResourceType.B, 'myData')         // Throws error

答案 1 :(得分:0)

在这种情况下,Typescript无法理解id永远不会是undefined,因为?将该参数声明为可选参数。

我不知道是否可以正确键入函数以按预期工作(我不知道该怎么做),但是可以消除错误的快速解决方案是提供带有无效合并的默认值:

type === ResourceType.B 
   ? myFunc(id ?? '') // Here typescript is happy, because there is a string fallback if id is undefined
   : yourFunc(data)

答案 2 :(得分:-3)

简单地做

options.filters = [['stage', 'anyof', ['CUSTOMER']]];

您的问题就解决了