函数类型的可选参数
Optional parameter to function type
假设我有以下(琐碎的)flow.js示例:
type Example = (d: number, b?: string) => void
const f:Example = (d: number, boo: string) => {}
编译失败:
const f:Example = (d: number, boo: string) => {}
^ Cannot assign function to `f` because string [1] is incompatible with undefined [2] in the second argument.
References:
3: const f:Example = (d: number, boo: string) => {}
^ [1]
1: type Example = (d: number, b?: string) => void
^ [2]
我想知道为什么?我认为第二个参数 (b) 被注释为可选的,例如如果它不存在那很好,但如果它存在它必须是一个字符串?
显然这是不准确的。这里发生的事情的实际解释是什么?我怎样才能得到我想要的行为(例如,一个函数接受一个或两个参数,当第二个参数存在时它必须是一个字符串)
可选参数?
表示调用者可以提供也可以不提供参数。 不是意味着特定的被调用者可以选择是否忽略参数。
错误告诉您函数 f
总是需要一个字符串参数,即使它并不总是提供,根据 Example
类型。
您可能想要做的是:
type Example = (d: number, b: string) => void
const f: Example = (d: number, boo: string) => {}
const g: Example = (d: number) => {}
Try it out
这是有效的,因为总是提供字符串参数,但被调用者可以选择是否使用该参数。
假设我有以下(琐碎的)flow.js示例:
type Example = (d: number, b?: string) => void
const f:Example = (d: number, boo: string) => {}
编译失败:
const f:Example = (d: number, boo: string) => {}
^ Cannot assign function to `f` because string [1] is incompatible with undefined [2] in the second argument.
References:
3: const f:Example = (d: number, boo: string) => {}
^ [1]
1: type Example = (d: number, b?: string) => void
^ [2]
我想知道为什么?我认为第二个参数 (b) 被注释为可选的,例如如果它不存在那很好,但如果它存在它必须是一个字符串?
显然这是不准确的。这里发生的事情的实际解释是什么?我怎样才能得到我想要的行为(例如,一个函数接受一个或两个参数,当第二个参数存在时它必须是一个字符串)
可选参数?
表示调用者可以提供也可以不提供参数。 不是意味着特定的被调用者可以选择是否忽略参数。
错误告诉您函数 f
总是需要一个字符串参数,即使它并不总是提供,根据 Example
类型。
您可能想要做的是:
type Example = (d: number, b: string) => void
const f: Example = (d: number, boo: string) => {}
const g: Example = (d: number) => {}
Try it out
这是有效的,因为总是提供字符串参数,但被调用者可以选择是否使用该参数。