为具有默认值的参数键入注释 [英] type annotation for parameter with default value

查看:59
本文介绍了为具有默认值的参数键入注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下函数定义中:

 function foo(a: number = 42): number {return a+1;}

a: number注释的语义是什么?

… what are the semantics of the a: number annotation?

是说变量 a 里面总是有一个值 函数的主体,还是说客户程序员在进行调用时应始终提供一个值?

Is it saying that variable a will always have a value inside the body of the function or is it saying that client programmers should always supply a value when they make the call?

我注意到下面的两个代码片段都进行了类型检查,没有错误(流箱为0.57.3):

I've noticed that both the below code snippets type-check with no errors (with flow-bin 0.57.3):

代码段1

function foo(a: number = 42): number {return a+1;}
type FooT= (a: number)=> number

(foo: FooT)

foo();

(尝试这里)

代码段2

function foo(a: ?number = 42): number {return a+1;}
type FooT = (a: ?number)=> number

(foo: FooT)

foo();

(尝试这里)

在这种情况下,建议的注释方式是什么?

What is the suggested way to annotate in such a case?

我的首选方式是#2,因为客户端程序员只需要查看FooT类型的定义即可认识到该参数是可选的.这使我可以告诉用户我的 库:仅查看函数的类型(FooT)".

My preference is with way #2 as the client programmer only has to look at the definition of the FooT type to realize that the parameter is optional. This allows me to tell users of my library: "simply look at the type of the function (FooT)".

使用方法1时,我不得不告诉他们函数的类型(FooT)似乎暗示需要一个参数,但实际上并不是因为,请看一下实现,则提供默认值."

Whereas with way #1 I have to tell them "the type of the function (FooT) seems to suggest that an argument is required, but in fact it isn't because, see, if you look at the implementation, a default value is supplied".

那么,哪个片段更惯用呢?

So, which snippet is more idiomatic?

请注意,相关问题似乎有一个答案,似乎暗示可以将类型注释为在函数的实现中是必需的,在声明中是可选的.但这在这种情况下似乎不起作用.例如.以下内容不会进行类型检查:

Note that there is an answer to a related question that seems to suggest that it is possible to annotate the type as mandatory in the implementation of a function and as optional in the declaration. But this doesn't seem to work in this case. E.g. the following doesn't type-check:

function foo(a: number = 42): number {return a+1;}
type FooT = (a: ?number)=> number

(foo: FooT)

foo();

(尝试这里)

推荐答案

您可以选择:

function foo(a: number = 42): number {return a+1;}
type FooT = (a?: number)=> number

(foo: FooT)

foo();

请注意类型定义中的?位置:

Pay attention to ? position in type definition:

(a?: number)-可选参数

vs

(a: ?number)-也许类型

两者之间的唯一区别是可选参数不能为空,就像

The only difference between the two is that the optional parameter can't be null, just like a parameter with default value

这篇关于为具有默认值的参数键入注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆