参数有默认值时定义类型的语法是什么? [英] What is the syntax for defining a type when parameter has a default value?
问题描述
在具有默认值的情况下,如何定义config
参数的类型?
How do I define the type of the config
parameter given that it has a default value?
function (config = {}) {};
推荐答案
function f(config: Object = {}) {}
或更笼统地说:
function f(p: T = v) {}
其中T
是类型,而v
是类型T
的值.
where T
is a type, and v
is a value of type T
.
有趣的是,函数f
的类型是(p?: T): void
.也就是说,Flow知道提供默认值会使该参数成为可选参数.您不必显式地将参数类型设为可选,尽管这不会造成损害.
Interestingly, the type of function f
is (p?: T): void
. That is, Flow understands that providing a default value makes the parameter optional. You don't need to explicitly make the parameter type optional—although it doesn't hurt.
在.js.flow
文件中编写declare function
语句时,不能包含默认值;否则,不能使用默认值.这会导致错误.因此,您必须明确声明该参数是可选的:
When writing declare function
statement in a .js.flow
file, you can't include the default value; it will cause an error. So you must explicitly declare that the parameter is optional:
declare function f(p?: T): void;
这篇关于参数有默认值时定义类型的语法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!