参数有默认值时定义类型的语法是什么? [英] What is the syntax for defining a type when parameter has a default value?

查看:86
本文介绍了参数有默认值时定义类型的语法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在具有默认值的情况下,如何定义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屋!

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