【发布时间】:2017-06-17 16:44:20
【问题描述】:
我有一个处理两种类型参数的函数:字符串和对象。预期有 3 种不同的对象结构。这构成了多达 4 种可能的类型:
type URL = string;
type Item = {| href: string |};
type ItemList = {| results: Item[] |};
type Params = {| offset?: number, limit?: number |};
所以函数的选项类型是:
type Options = URL | Item | ItemList | Params;
这是实际的功能:
// No properties of "Params" are required
// so if they're all omitted, Params === {}
function request(opts: Options = {}) {
if (typeof opts === 'string') {
return 'opts is an URL';
}
if (typeof opts.href === 'string') {
return 'opts is an item';
}
if (Array.isArray(opts.results)) {
return 'opts is a list of items';
}
// Three of the four types are caught
// we're left with "Params" which may or may not
// have a "offset" and "limit" property.
// Destructuring to undefined values is fine here.
// Still, flow complains about the type not being met.
const { offset, limit } = opts;
return 'opts are parameters';
}
Flow 抱怨一些事情:
-
opts = {}引发不兼容错误。由于不需要Params的属性,空对象不应该也匹配吗?请注意,opts = { offset: undefined }会清除错误。 - 声明未找到属性“offset”和“limit”。由于它们都不是必需的,
undefined不应该是有效值吗?从而解构罚款?
总结一下我的问题:
你如何定义一个类型来接受不同类型的对象,其中一个没有必需的属性?
【问题讨论】:
标签: javascript types flowtype